取自这个 Stackoverflow答案,我想出了:
public static Image Resize(this Image image, int maxWidth = 0, int maxHeight = 0)
{
if (maxWidth == 0)
maxWidth = image.Width;
if (maxHeight == 0)
maxHeight = image.Height;
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
要调整图像的大小,指定其最大宽度:
var _image = Image.FromStream(Source);
var _thumbImage = _image.Resize(100);
要调整图像的大小,指定其 maxHeight:
var _image = Image.FromStream(Source);
var _thumbImage = _image.Resize(maxHeight: 100);