項目中常常用到圖片的大小太大,這就須要圖片的無損壓縮。具體實現的代碼以下:c#
首先引用一下命名空間:spa
1 using System.Drawing.Imaging; 2 using System.Drawing; 3 using System.Drawing.Drawing2D;
實現方法:code
1 #region GetPicThumbnail 2 /// <summary> 3 /// 無損壓縮圖片 4 /// </summary> 5 /// <param name="sFile">原圖片</param> 6 /// <param name="dFile">壓縮後保存位置</param> 7 /// <param name="dHeight">高度</param> 8 /// <param name="dWidth">寬度</param> 9 /// <param name="flag">壓縮質量 1-100</param> 10 /// <returns></returns> 11 12 public bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag) 13 { 14 System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile); 15 ImageFormat tFormat = iSource.RawFormat; 16 int sW = 0, sH = 0; 17 //按比例縮放 18 Size tem_size = new Size(iSource.Width, iSource.Height); 19 if (tem_size.Width > dHeight || tem_size.Width > dWidth) //將**改爲c#中的或者操做符號 20 { 21 if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth)) 22 { 23 sW = dWidth; 24 sH = (dWidth * tem_size.Height) / tem_size.Width; 25 } 26 else 27 { 28 sH = dHeight; 29 sW = (tem_size.Width * dHeight) / tem_size.Height; 30 } 31 } 32 else 33 { 34 sW = tem_size.Width; 35 sH = tem_size.Height; 36 } 37 38 Bitmap ob = new Bitmap(dWidth, dHeight); 39 Graphics g = Graphics.FromImage(ob); 40 g.Clear(Color.WhiteSmoke); 41 g.CompositingQuality = CompositingQuality.HighQuality; 42 g.SmoothingMode = SmoothingMode.HighQuality; 43 g.InterpolationMode = InterpolationMode.HighQualityBicubic; 44 g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); 45 g.Dispose(); 46 //如下代碼爲保存圖片時,設置壓縮質量 47 EncoderParameters ep = new EncoderParameters(); 48 long[] qy = new long[1]; 49 qy[0] = flag;//設置壓縮的比例1-100 50 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); 51 ep.Param[0] = eParam; 52 try 53 { 54 ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); 55 56 ImageCodecInfo jpegICIinfo = null; 57 58 for (int x = 0; x < arrayICI.Length; x++) 59 { 60 if (arrayICI[x].FormatDescription.Equals("JPEG")) 61 { 62 jpegICIinfo = arrayICI[x]; 63 break; 64 } 65 } 66 if (jpegICIinfo != null) 67 { 68 ob.Save(dFile, jpegICIinfo, ep);//dFile是壓縮後的新路徑 69 } 70 else 71 { 72 ob.Save(dFile, tFormat); 73 } 74 return true; 75 } 76 catch 77 { 78 return false; 79 } 80 finally 81 { 82 iSource.Dispose(); 83 ob.Dispose(); 84 85 } 86 } 87 #endregion