朋友開了網店,想讓我幫忙作一些小工具,其中就包含了圖片無損壓縮的需求,這一類的軟件和代碼在網上有不少,可是真正實用的符合本身定製化需求的沒幾個,因而就想着本身DIY一下(本身動手豐衣足食^o^),並貼出核心代碼供你們學習和參考工具
/// <summary> /// 無損壓縮圖片 /// </summary> /// <param name="sFile">原圖片地址</param> /// <param name="dFile">壓縮後保存圖片地址</param> /// <param name="flag">壓縮質量(數字越小壓縮率越高)1-100</param> /// <returns></returns> public static bool CompressImage(string sFile, string dFile, int flag = 90) { Image iSource = Image.FromFile(sFile); ImageFormat tFormat = iSource.RawFormat; int dHeight = iSource.Height / 2; int dWidth = iSource.Width / 2; int sW, sH; //按比例縮放 Size tem_size = new Size(iSource.Width, iSource.Height); if (tem_size.Width > dHeight || tem_size.Width > dWidth) { if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth)) { sW = dWidth; sH = (dWidth * tem_size.Height) / tem_size.Width; } else { sH = dHeight; sW = (tem_size.Width * dHeight) / tem_size.Height; } } else { sW = tem_size.Width; sH = tem_size.Height; } Bitmap ob = new Bitmap(dWidth, dHeight); Graphics g = Graphics.FromImage(ob); g.Clear(Color.WhiteSmoke); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); g.Dispose(); //如下代碼爲保存圖片時,設置壓縮質量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//設置壓縮的比例1-100 EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = arrayICI.FirstOrDefault(t => t.FormatDescription.Equals("JPEG")); if (jpegICIinfo != null) { ob.Save(dFile, jpegICIinfo, ep);//dFile是壓縮後的新路徑 } else { ob.Save(dFile, tFormat); } return true; } catch { return false; } finally { iSource.Dispose(); ob.Dispose(); } }