上傳頭像、商品圖、文件縮圖時,需在限定最大寬高框內,保持原始長寬比縮放,避免變形。本文提供一個純數學計算的靜態方法,不依賴任何影像庫,回傳 Size 結構,極輕量、高效能。
using System;
using System.Drawing;
public static class ImageResizeHelper
{
///
/// 計算等比例縮放後的尺寸
///
/// 最大寬度
/// 最大高度
/// 原始寬度
/// 原始高度
/// 縮放後尺寸 (寬, 高)
public static Size CalculateProportionalSize(int maxWidth, int maxHeight, int originalWidth, int originalHeight)
{
if (originalWidth <= 0 || originalHeight <= 0) throw new ArgumentException("原始尺寸必須大於 0");
if (maxWidth <= 0 || maxHeight <= 0) throw new ArgumentException("最大尺寸必須大於 0");
double srcW = originalWidth, srcH = originalHeight;
double maxW = maxWidth, maxH = maxHeight;
// 原圖已小於限制,不縮放
if (srcW <= maxW && srcH <= maxH)
return new Size(originalWidth, originalHeight);
double srcRatio = srcW / srcH;
double maxRatio = maxW / maxH;
double destW, destH;
if (srcRatio > maxRatio)
{
// 以寬度為基準
destW = maxW;
destH = maxW / srcRatio;
}
else
{
// 以高度為基準
destH = maxH;
destH = maxH; // 修正:應為 destH = maxH
destW = maxH * srcRatio;
}
return new Size((int)Math.Round(destW), (int)Math.Round(destH));
}
}
public static Size CalculateProportionalSize(int maxWidth, int maxHeight, int originalWidth, int originalHeight)
{
if (originalWidth <= 0 || originalHeight <= 0) throw new ArgumentException("原始尺寸必須大於 0");
if (maxWidth <= 0 || maxHeight <= 0) throw new ArgumentException("最大尺寸必須大於 0");
double srcW = originalWidth, srcH = originalHeight;
double maxW = maxWidth, maxH = maxHeight;
if (srcW <= maxW && srcH <= maxH)
return new Size(originalWidth, originalHeight);
double srcRatio = srcW / srcH;
double maxRatio = maxW / maxH;
double destW, destH;
if (srcRatio > maxRatio)
{
destW = maxW;
destH = maxW / srcRatio;
}
else
{
destH = maxH;
destW = maxH * srcRatio;
}
return new Size((int)Math.Round(destW), (int)Math.Round(destH));
}
// 原圖 1920x1080,限制 800x600
Size newSize = ImageResizeHelper.CalculateProportionalSize(800, 600, 1920, 1080);
// 結果: 800x450 (16:9 保持)
// 原圖 800x1200 (直向),限制 400x400
Size newSize2 = ImageResizeHelper.CalculateProportionalSize(400, 400, 800, 1200);
// 結果: 267x400 (2:3 保持)
// 實際縮放 (搭配 System.Drawing)
using (Image src = Image.FromFile("input.jpg"))
{
Size target = ImageResizeHelper.CalculateProportionalSize(800, 600, src.Width, src.Height);
using (Bitmap bmp = new Bitmap(target.Width, target.Height))
using (Graphics g = Graphics.FromImage(bmp))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(src, 0, 0, target.Width, target.Height);
bmp.Save("output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
public enum ResizeMode { Fit, Fill } // Fit=含蓋(留白), Fill=裁切填滿
public static Size CalculateSize(int maxW, int maxH, int srcW, int srcH, ResizeMode mode)
{
if (mode == ResizeMode.Fit) return CalculateProportionalSize(maxW, maxH, srcW, srcH);
// Fill: 以較大比例縮放,再置中裁切
double scale = Math.Max((double)maxW / srcW, (double)maxH / srcH);
return new Size((int)Math.Round(srcW * scale), (int)Math.Round(srcH * scale));
}
Image.GetThumbnailImageAbort 回調或 Graphics 高品質插值。