以往做圖片縮放的時候都是對原圖片完整進行縮放,但是這樣會造成圖片周圍有白邊產生,但是有的客戶希望圖片無拉伸但是仍然填滿縮放區域,這樣只好對圖片進行剪裁,但是以圖片的左上方頂點為原點進行剪裁往往會剪掉一些需要的區域,一搬拍照都是把需要的部分拍在最中間,所以下面的算法是進行兩端剪裁,代碼如下:
1 /// <summary> 2 /// 生成縮略圖並剪裁算法 3 /// </summary> 4 /// <param name="pathImageFrom">原始圖片位置</param> 5 /// <param name="pathImageTo">生成圖片存放位置</param> 6 /// <param name="width">生成圖片的寬度</param> 7 /// <param name="height">生成圖片的高度</param> 8 public void GenThumbnail(string pathImageFrom, string pathImageTo, int width, int height) 9 { 10 Image imageFrom = null; 11 try 12 { 13 imageFrom = Image.FromFile(pathImageFrom); 14 } 15 catch 16 { 17 throw new FileNotFoundException("圖片不存在!"); 18 } 19 if (imageFrom == null) 20 { 21 return; 22 } 23 // 原始圖片的寬度及高度 24 int imageFromWidth = imageFrom.Width; 25 int imageFromHeight = imageFrom.Height; 26 27 // 需要生成的縮略圖在上述"畫布"上的起點位置 28 int X = 0; 29 int Y = 0; 30 // 根據原始圖片及欲生成的縮略圖尺寸,計算縮略圖的實際尺寸及原始圖片需要裁剪后的左邊或上面坐標 31 if (height * imageFromWidth > width * imageFromHeight) 32 { 33 X = (imageFromWidth - width * imageFromHeight / height) / 2; 34 } 35 else 36 { 37 Y = (imageFromHeight - height * imageFromWidth / width) / 2; 38 } 39 //圖片經過縮放剪裁后的寬和高 40 int W = 0; 41 int H = 0; 42 W = X > 0 ? imageFromWidth - X * 2 : imageFromWidth; 43 H = Y > 0 ? imageFromHeight - Y * 2 : imageFromHeight; 44 // 創建畫布 45 Bitmap bmp = new Bitmap(width, height); 46 Graphics g = Graphics.FromImage(bmp); 47 // 用白色清空 48 g.Clear(Color.White); 49 // 指定高質量的雙三次插值法。執行預篩選以確保高質量的收縮。此模式可產生質量最高的轉換圖像。 50 g.InterpolationMode = InterpolationMode.HighQualityBicubic; 51 // 指定高質量、低速度呈現。 52 g.SmoothingMode = SmoothingMode.HighQuality; 53 // 在指定位置並且按指定大小繪制指定的 Image 的指定部分。 54 g.DrawImage(imageFrom, new Rectangle(0, 0, width, height), new Rectangle(X, Y, W, H), GraphicsUnit.Pixel); 55 try 56 { 57 //經測試 .jpg 格式縮略圖大小與質量等最優 58 bmp.Save(pathImageTo, ImageFormat.Jpeg); 59 } 60 catch 61 { 62 63 } 64 finally 65 { 66 //顯示釋放資源 67 imageFrom.Dispose(); 68 bmp.Dispose(); 69 g.Dispose(); 70 } 71 }