萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 生成圖片縮略圖完整實現:Image.GetThumbnailImage 與按比例縮放

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; }

關鍵 API 對比

高質量版本 (推薦生產環境)

public static Image ResizeImage(Image src, int maxWidth, int maxHeight)
{
    var ratio = Math.Min((double)maxWidth / src.Width, (double)maxHeight / src.Height);
    var newWidth = (int)(src.Width * ratio);
    var newHeight = (int)(src.Height * ratio);

    var dest = new Bitmap(newWidth, newHeight);
    using (var g = Graphics.FromImage(dest))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.DrawImage(src, 0, 0, newWidth, newHeight);
    }
    return dest;
}

資源管理鐵律

  • Image、Graphics、Bitmap 實現 IDisposable,必須用 using 或 try/finally Dispose()。
  • 文件流、內存流同理。
  • ASP.NET 處理上傳文件時,PostedFile.InputStream 直接讀取避免臨時文件。

常見坑

  • 未按比例縮放 → 圖片變形 (代碼中已修正:newHeight = height * newWidth / width)。
  • 未釋放 GDI+ 對象 → 內存洩漏、進程句柄耗盡、後續請求報「GDI+ 一般性錯誤」。
  • 縮略圖文件名衝突 → 用 GUID、時間戳+隨機數、哈希值命名。

規範的縮略圖生成流程,是 Web 圖片處理穩定性的基石。

copyright © 萬盛學電腦網 all rights reserved
方法優點缺點適用場景
Image.GetThumbnailImage簡單、內部優化、返回新 Image 對象質量一般、不支持高質量插值模式Web 縮略圖、預覽圖
Graphics.DrawImage + InterpolationMode.HighQualityBicubic高質量、可控插值、支持旋轉/裁剪代碼較多、需手動 Dispose高質量壓縮、打印級輸出
Image.GetThumbnailImageAbort 回調可中斷長時間縮放罕用大圖批量處理