功能特性
- 四種生成模式:指定寬高(可能變形)、指定寬(高按比例)、指定高(寬按比例)、指定寬高裁剪(不變形,居中截取)
- 高質量插值:
InterpolationMode.High + SmoothingMode.HighQuality
- 透明背景填充,JPEG 輸出
- 完整資源釋放:
Image、Bitmap、Graphics 均在 finally 中 Dispose
核心代碼
public static void MakeThumbnail(
string originalImagePath,
string thumbnailPath,
int width,
int height,
string mode)
{
using (Image originalImage = Image.FromFile(originalImagePath))
{
int towidth = width, toheight = height;
int x = 0, y = 0, ow = originalImage.Width, oh = originalImage.Height;
switch (mode)
{
case "HW": // 指定寬高,可能變形
break;
case "W": // 指定寬,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case "H": // 指定高,寬按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case "Cut": // 指定寬高裁剪,不變形
if ((double)originalImage.Width / originalImage.Height > (double)towidth / toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
break;
}
using (Bitmap bitmap = new Bitmap(towidth, toheight))
using (Graphics g = Graphics.FromImage(bitmap))
{
g.InterpolationMode = InterpolationMode.High;
g.SmoothingMode = SmoothingMode.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(originalImage,
new Rectangle(0, 0, towidth, toheight),
new Rectangle(x, y, ow, oh),
GraphicsUnit.Pixel);
bitmap.Save(thumbnailPath, ImageFormat.Jpeg);
}
}
}
關鍵點解析
| 技術點 | 說明 |
Graphics.DrawImage 重載 | 目標矩形、源矩形、單位像素,實現裁剪縮放 |
| 插值模式 | High 雙三次插值,縮放品質最佳 |
| 平滑模式 | HighQuality 抗鋸齒 |
| 資源管理 | using 確保非托管資源及時釋放,防內存洩漏 |
調用示例
// 等比縮放寬 200px
MakeThumbnail(@"C:\src.jpg", @"C:\thumb.jpg", 200, 0, "W");
// 裁剪為 150x150 正方形
MakeThumbnail(@"C:\src.jpg", @"C:\thumb.jpg", 150, 150, "Cut");
擴展建議
- 支持 PNG 輸出保留透明通道
- 添加水印、圖片旋轉、EXIF 方向自動修正
- 大圖分塊處理避免 LOH 內存壓力