萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 動態產生縮圖:GetThumbnailImage 完整實作

伺服器端即時生成 JPEG 縮圖

使用 `System.Drawing.Image.GetThumbnailImage` 快速產生縮圖,無需儲存實體檔案,適合動態圖庫、商品列表預覽。

核心函數 (VB.NET)

Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging

Function CreateJPEGThumbnail(inSourceFile As String, 
                             inDestinationFile As String, 
                             ThumbWidth As Integer, 
                             ThumbHeight As Integer) As Boolean
    Dim imageFile As Image
    Dim outputFstream As New FileStream(inSourceFile, FileMode.Open, FileAccess.Read)
    
    Dim callback As Image.GetThumbnailImageAbort = AddressOf ImageAbortDummyCallback
    
    imageFile = Image.FromStream(outputFstream)
    imageFile = imageFile.GetThumbnailImage(ThumbWidth, ThumbHeight, callback, IntPtr.Zero)
    
    imageFile.Save(inDestinationFile, ImageFormat.Jpeg)
    
    outputFstream.Close()
    outputFstream = Nothing
    imageFile = Nothing
    Return True
End Function

Function ImageAbortDummyCallback() As Boolean
    Return False  ' 不中止
End Function

C# 版本 (現代專案常用)

public static void GenerateThumbnail(string sourcePath, string destPath, int width, int height)
{
    using (var src = Image.FromFile(sourcePath))
    using (var thumb = src.GetThumbnailImage(width, height, () => false, IntPtr.Zero))
    {
        thumb.Save(destPath, ImageFormat.Jpeg);
    }
}

// 更高品質:使用 Graphics.DrawImage (雙三次插值)
public static void GenerateHighQualityThumbnail(string sourcePath, string destPath, int width, int height)
{
    using (var src = Image.FromFile(sourcePath))
    using (var thumb = new Bitmap(width, height))
    using (var g = Graphics.FromImage(thumb))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.DrawImage(src, 0, 0, width, height);
        thumb.Save(destPath, ImageFormat.Jpeg);
    }
}

ASP.NET Core / 現代架構建議

  • **不要**在 Web 請求中同步處理大量圖片 → 阻塞執行緒池。
  • 使用 **背景任務** (Hangfire/Quartz/HostedService) 非同步生成縮圖並儲存至 Blob/檔案系統。
  • 前端直接請求縮圖 URL,若不存在觸發生成 (或回傳 404 由前端重試)。
  • 考慮 `ImageSharp`、`SkiaSharp` 等跨平台純 .NET 圖片庫,取代 `System.Drawing.Common` (僅支援 Windows/Linux 需 libgdiplus)。

快取策略

// 輸出快取標頭
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetMaxAge(TimeSpan.FromDays(30));
Response.Cache.SetETag(ComputeETag(sourcePath, width, height));

注意: `System.Drawing` 在 ASP.NET Core / Linux 容器中已棄用/受限,新專案請改用 SixLabors.ImageSharp (Apache 2.0 授權) 或 SkiaSharp。

copyright © 萬盛學電腦網 all rights reserved