ASP.NET 文件上傳後生成縮略圖是常見需求。本文展示完整處理流程:保存原圖 → 計算目標尺寸 (保持比例) → GetThumbnailImage 生成 → 保存縮略圖 → 釋放資源,並處理不同業務場景下的尺寸邏輯。
if (fileupload.PostedFile != null)
{
// 1. 獲取原始文件名、擴展名
string originalName = fileupload.PostedFile.FileName;
int dotIndex = originalName.LastIndexOf(".");
string ext = originalName.Substring(dotIndex); // 含點
// 2. 生成唯一文件名: 日期 + 文件大小
DateTime now = DateTime.Now;
string newName = now.DayOfYear.ToString() + fileupload.PostedFile.ContentLength.ToString();
// 3. 保存原圖
string uploadDir = Server.MapPath("upload/");
string originalPath = Path.Combine(uploadDir, newName + ext);
fileupload.PostedFile.SaveAs(originalPath);
// 4. 生成縮略圖
using (Image image = Image.FromFile(originalPath))
{
int width = image.Width;
int height = image.Height;
int newWidth, newHeight;
// 業務邏輯: 不同頁面/分類對應不同寬度
if (firstpageshow.SelectedValue == "1" && fenlei.SelectedValue == "5")
{
newWidth = 203; newHeight = 86;
}
else if (isweekman.SelectedValue == "1")
{
newWidth = 171; newHeight = 111;
}
else if (firstpageshow.SelectedValue == "1" && fenlei.SelectedValue == "3")
{
newWidth = 171; newHeight = 111;
}
else
{
newWidth = 62; newHeight = 80;
}
// 關鍵: 按原圖比例計算實際高度, 防止變形
newHeight = height * newWidth / width;
// 5. 生成縮略圖 (GetThumbnailImage 內部使用較快的縮放算法)
Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
using (Image thumb = image.GetThumbnailImage(newWidth, newHeight, callback, IntPtr.Zero))
{
string thumbPath = Path.Combine(uploadDir, "small_" + newName + ext);
thumb.Save(thumbPath, image.RawFormat); // 保持原格式
}
}
// 6. 返回路徑供頁面顯示/入庫
string pic = "upload/" + newName + ext;
string smallPic = "upload/small_" + newName + ext;
}
// 回調函數 (通常直接返回 false 繼續)
public bool ThumbnailCallback() { return false; }
| 方法 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| Image.GetThumbnailImage | 簡單、內部優化、返回新 Image 對象 | 質量一般、不支持高質量插值模式 | Web 縮略圖、預覽圖 |
| Graphics.DrawImage + InterpolationMode.HighQualityBicubic | 高質量、可控插值、支持旋轉/裁剪 | 代碼較多、需手動 Dispose | 高質量壓縮、打印級輸出 |
| Image.GetThumbnailImageAbort 回調 | 可中斷長時間縮放 | 罕用 | 大圖批量處理 |