萬盛學電腦網

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

.NET 圖片處理核心函式庫:等比縮放、高質量縮略圖生成與檔案儲存

圖片上傳、縮略圖生成、等比縮放是 Web 應用的高頻剛需。本文提供生產級、高效能、記憶體友善的 System.Drawing (GDI+) 封裝函式,涵蓋尺寸計算、雙三次插值高質量渲染、透明背景保留、檔案串流處理全流程。

核心功能模組

  1. GetNewSize:計算等比縮放後實際尺寸,支援單邊限制 (僅寬/高) 與雙邊限制。
  2. GetThumbNailImage (Image → Image):對記憶體中 Image 物件生成高質量縮略圖。
  3. GetThumbNailImage (filePath → Image):從檔案載入原圖並生成縮略圖,自動釋放原圖資源。
  4. MakeThumbNail:一站式從原圖檔案生成縮略圖並儲存至目標路徑。

完整原始碼 (C#)

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

效能與記憶體優化要點

  • 避免 Large Object Heap (LOH) 碎片:大圖片解碼後位元組陣列 > 85KB 進入 LOH,建議使用 Image.FromStream(..., false, false) 延遲載入或分塊處理。
  • 及時 Dispose: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+ 平台相依與記憶體管理痛點。

copyright © 萬盛學電腦網 all rights reserved