C#:如何使用最大高度按比例调整图像大小
作者:互联网
我需要在不改变宽高比的情况下按比例调整图像大小.我有使用固定高度和宽度调整大小的代码,但我需要按最大高度(比如600像素)按比例调整图像大小.如何修改代码以满足我的要求?
public static void Main()
{
var image = Image.FromFile(@"c:\logo.png");
var newImage = ScaleImage(image, 300, 400);
newImage.Save(@"c:\test.png", ImageFormat.Png);
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
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;
}
请提供宝贵的意见.
解决方法:
这几乎感觉很容易,我觉得我错过了什么.无论如何,这不会有诀窍吗?
public static Image ScaleImage(Image image, int maxHeight)
{
var ratio = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}
标签:c,asp-net,aspect-ratio,image-resizing 来源: https://codeday.me/bug/20190530/1183515.html