封裝 System.Drawing 命名空間,提供四種多載方法:依指定寬高產生 Image 物件、依指定寬高儲存檔案、依比例縮放產生物件、依比例縮放儲存檔案。支援 JPEG 輸出,並統一例外處理與資源釋放。
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
public class ImageProcessor
{
private readonly Image _sourceImage;
public string ErrorMessage { get; private set; }
public ImageProcessor(string imagePath)
{
if (!File.Exists(imagePath))
throw new FileNotFoundException("找不到圖片檔案", imagePath);
_sourceImage = Image.FromFile(imagePath);
ErrorMessage = string.Empty;
}
/// 回呼函式,GetThumbnailImage 要求但通常不需實作邏輯
private bool ThumbnailCallback() => false;
/// 依指定寬高產生縮圖 Image 物件
public Image GetThumbnail(int width, int height)
{
try
{
var callback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
return _sourceImage.GetThumbnailImage(width, height, callback, IntPtr.Zero);
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return null;
}
}
/// 依指定寬高產生並儲存縮圖
public bool SaveThumbnail(int width, int height, string destPath)
{
try
{
using (var thumb = GetThumbnail(width, height))
{
if (thumb == null) return false;
Directory.CreateDirectory(Path.GetDirectoryName(destPath));
thumb.Save(destPath, ImageFormat.Jpeg);
}
return true;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return false;
}
}
/// 依比例縮放產生縮圖 Image 物件
public Image GetThumbnail(double scale)
{
if (scale <= 0 || scale > 1) throw new ArgumentOutOfRangeException(nameof(scale), "縮放比例需在 0~1 之間");
int w = (int)(_sourceImage.Width * scale);
int h = (int)(_sourceImage.Height * scale); // 修正原碼 Width 重複使用錯誤
return GetThumbnail(w, h);
}
/// 依比例縮放並儲存縮圖
public bool SaveThumbnail(double scale, string destPath)
{
try
{
using (var thumb = GetThumbnail(scale))
{
if (thumb == null) return false;
Directory.CreateDirectory(Path.GetDirectoryName(destPath));
thumb.Save(destPath, ImageFormat.Jpeg);
}
return true;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return false;
}
}
/// 釋放原始圖片資源
public void Dispose() => _sourceImage?.Dispose();
}
// 產生 200x150 縮圖並存檔
using (var processor = new ImageProcessor(@"C:\Images\photo.jpg"))
{
if (processor.SaveThumbnail(200, 150, @"C:\Thumbs\photo_thumb.jpg"))
Console.WriteLine("縮圖產生成功");
else
Console.WriteLine("失敗:" + processor.ErrorMessage);
}
// 依 50% 比例產生 Image 物件供後續處理
using (var processor = new ImageProcessor(@"C:\Images\photo.jpg"))
{
using (var thumb = processor.GetThumbnail(0.5))
{
if (thumb != null) pictureBox1.Image = thumb;
}
}
ImageHeight = ResourceImage.Width * Percent 導致長寬比失真,已修正為 Height * Percent。IDisposable 模式,確保 Image 物件與檔案串流正確釋放,避免 GDI+ 記憶體洩漏。伺服器需安裝 libgdiplus(Linux Docker 環境)或啟用 Windows 功能「包含桌面體驗的伺服器圖形化管理工具」,否則 System.Drawing 會擲出 TypeInitializationException。