圖片上傳、縮略圖生成、等比縮放是 Web 應用的高頻剛需。本文提供生產級、高效能、記憶體友善的 System.Drawing (GDI+) 封裝函式,涵蓋尺寸計算、雙三次插值高質量渲染、透明背景保留、檔案串流處理全流程。
Image 物件生成高質量縮略圖。using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
public static class ImageHelper
{
///
/// 計算等比縮放後的實際尺寸 (不放大,僅縮小或保持原尺)
///
public static Size GetNewSize(int maxWidth, int maxHeight, int originalWidth, int originalHeight)
{
if (maxWidth <= 0 || maxHeight <= 0)
throw new ArgumentException("目標尺寸必須大於 0");
double srcW = originalWidth, srcH = originalHeight;
double dstW = maxWidth, dstH = maxHeight;
// 原圖已小於目標框,不放大
if (srcW <= dstW && srcH <= dstH)
return new Size(originalWidth, originalHeight);
// 計算縮放比例,取較小者確保完整放入目標框
double ratio = Math.Min(dstW / srcW, dstH / srcH);
int newW = (int)Math.Round(srcW * ratio);
int newH = (int)Math.Round(srcH * ratio);
return new Size(newW, newH);
}
///
/// 生成高質量縮略圖 (來源為 Image 物件)
///
public static Image GetThumbNailImage(Image originalImage, int maxWidth, int maxHeight)
{
if (originalImage == null) throw new ArgumentNullException(nameof(originalImage));
Size thumbSize = GetNewSize(maxWidth, maxHeight, originalImage.Width, originalImage.Height);
var thumbnail = new Bitmap(thumbSize.Width, thumbSize.Height, PixelFormat.Format32bppArgb); // 支援透明通道
using (Graphics g = Graphics.FromImage(thumbnail))
{
// 高質量插值模式
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic; // 雙三次插值
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.Clear(Color.Transparent); // 透明背景,避免黑邊
// 核心繪製:來源矩形 → 目標矩形
g.DrawImage(originalImage,
new Rectangle(0, 0, thumbSize.Width, thumbSize.Height),
new Rectangle(0, 0, originalImage.Width, originalImage.Height),
GraphicsUnit.Pixel);
}
return thumbnail;
}
///
/// 生成高質量縮略圖 (來源為檔案路徑)
///
public static Image GetThumbNailImage(string imageFilePath, int maxWidth, int maxHeight)
{
if (!File.Exists(imageFilePath))
throw new FileNotFoundException("原圖檔案不存在", imageFilePath);
Image original = null;
try
{
original = Image.FromFile(imageFilePath);
// FromFile 會鎖定檔案,必須複製到記憶體才能釋放檔案鎖
using (var ms = new MemoryStream())
{
original.Save(ms, original.RawFormat);
var clone = Image.FromStream(ms);
original.Dispose(); // 釋放檔案鎖
original = clone;
}
return GetThumbNailImage(original, maxWidth, maxHeight);
}
catch
{
original?.Dispose();
throw;
}
}
///
/// 一站式:讀取原圖 → 生成縮略圖 → 儲存至目標檔案 (支援指定編碼器參數)
///
public static void MakeThumbNail(string originalFile, string thumbFile, int maxWidth, int maxHeight, long jpegQuality = 85L)
{
Image thumb = null;
try
{
thumb = GetThumbNailImage(originalFile, maxWidth, maxHeight);
// 確保目標目錄存在
string dir = Path.GetDirectoryName(thumbFile);
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
// 針對 JPEG 設定品質,其他格式使用預設編碼器
ImageCodecInfo encoder = GetEncoder(ImageFormat.Jpeg);
if (encoder != null && Path.GetExtension(thumbFile).Equals(".jpg", StringComparison.OrdinalIgnoreCase)
|| Path.GetExtension(thumbFile).Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
{
var ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(Encoder.Quality, jpegQuality);
thumb.Save(thumbFile, encoder, ep);
}
else
{
thumb.Save(thumbFile); // PNG/GIF/BMP 使用無損預設
}
}
finally
{
thumb?.Dispose();
}
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
return ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID == format.Guid);
}
}
// 1. 上傳處理中生成多種尺寸縮略圖
string uploadPath = Server.MapPath("~/Uploads/Original/photo.jpg");
string thumbDir = Server.MapPath("~/Uploads/Thumbs/");
ImageHelper.MakeThumbNail(uploadPath, Path.Combine(thumbDir, "photo_thumb_150.jpg"), 150, 150);
ImageHelper.MakeThumbNail(uploadPath, Path.Combine(thumbDir, "photo_thumb_300.jpg"), 300, 300);
ImageHelper.MakeThumbNail(uploadPath, Path.Combine(thumbDir, "photo_thumb_800.jpg"), 800, 600);
// 2. 記憶體流處理 (不落地原圖)
using (var ms = new MemoryStream(fileUpload.FileBytes))
using (var original = Image.FromStream(ms))
using (var thumb = ImageHelper.GetThumbNailImage(original, 200, 200))
using (var outStream = new MemoryStream())
{
thumb.Save(outStream, ImageFormat.Png);
byte[] thumbBytes = outStream.ToArray();
// 儲存至資料庫 / 雲端儲存 / 回傳前端 Base64
}
// 3. ASP.NET Core / .NET 6+ 跨平台注意
// System.Drawing.Common 僅支援 Windows/Linux (需 libgdiplus)。
// Linux 容器建議改用 ImageSharp (SixLabors.ImageSharp) 純託管庫:
// using SixLabors.ImageSharp;
// using SixLabors.ImageSharp.Processing;
// using (var img = Image.Load(stream)) { img.Mutate(x => x.Resize(new ResizeOptions { Mode = ResizeMode.Max, Size = new Size(200, 200) })); img.Save(outStream, new PngEncoder()); }
Image.FromStream(..., false, false) 延遲載入或分塊處理。Image、Graphics、Bitmap 實作 IDisposable,務必 using 或 try/finally 釋放非託管 GDI+ 資源,防止處理程序句柄洩漏。Image.FromFile 會獨佔檔案鎖定至 Dispose,Web 伺服器高併發下極易導致共用違規。務必複製到 MemoryStream 或直接用 Image.FromStream。EncoderParameters、ImageCodecInfo 可靜態快取,避免每次反射查找。以 InterpolationMode.HighQualityBicubic 為核心的高質量縮放、透明背景保留、JPEG 品質可控、資源嚴格釋放,構成了生產可用的圖片處理基石。隨著 .NET Core 跨平台演進,建議新專案遷移至 ImageSharp 或 SkiaSharp 純託管庫,徹底擺脫 GDI+ 平台相依與記憶體管理痛點。