/// <summary> /// 按比例缩放图片 /// </summary> /// <param name="source"></param> /// <param name="target"></param> /// <param name="destHeight"></param> /// <param name="destWidth"></param> /// <returns></returns> public static bool GetThumbnail(string source, string target, int destWidth = 1024, int destHeight = 800) { try { if (!File.Exists(source)) { return(false); } System.Drawing.Image imgSource = Image.FromFile(source); System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat; int sW = 0, sH = 0; // 按比例缩放 int sWidth = imgSource.Width; int sHeight = imgSource.Height; if (sHeight > destHeight || sWidth > destWidth) { if ((sWidth * destHeight) > (sHeight * destWidth)) { sW = destWidth; sH = (destWidth * sHeight) / sWidth; } else { sH = destHeight; sW = (sWidth * destHeight) / sHeight; } } else { sW = sWidth; sH = sHeight; } Bitmap outBmp = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage(outBmp); g.Clear(Color.Transparent); // 设置画布的描绘质量 g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel); g.Dispose(); // 以下代码为保存图片时,设置压缩质量 ImageCodecInfo myImageCodecInfo = GetEncoderInfo(FileContentType.GetMimeMapping(source)); EncoderParameters encoderParams = new EncoderParameters(); long[] quality = new long[1]; quality[0] = 100; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; imgSource.Dispose(); EncoderParameters myEncoderParameters = new EncoderParameters(1); myEncoderParameters.Param[0] = encoderParam; outBmp.Save(target, myImageCodecInfo, myEncoderParameters); return(true); } catch (Exception ex) { throw ex; } }
/// <summary> /// 压缩文件 /// </summary> /// <param name="srcFile"></param> /// <param name="destFile"></param> /// <param name="level"></param> public static void Compress(string srcFile, string destFile, long level) { Bitmap srcBitMap = new Bitmap(srcFile); Stream s = new FileStream(destFile, FileMode.Create); Compress(srcBitMap, s, level, FileContentType.GetMimeMapping(srcFile)); s.Close(); }
/// <summary> /// 图片压缩到字节数组 /// </summary> /// <param name="srcFile"></param> /// <param name="level">0-100</param> /// <returns></returns> public static byte[] CompressToBytes(string srcFile, long level) { byte[] bs = null; Bitmap srcBitMap = new Bitmap(srcFile); System.IO.MemoryStream ms = new MemoryStream(); Compress(srcBitMap, ms, level, FileContentType.GetMimeMapping(srcFile)); bs = ms.ToArray(); ms.Close(); return(bs); }