gpt4 book ai didi

C# : How to resize image proportionately with max height

转载 作者:太空狗 更新时间:2023-10-30 00:55:11 27 4
gpt4 key购买 nike

我需要在不改变宽高比的情况下按比例调整图像大小。我有代码可以使用固定的高度和宽度调整大小,但我需要按最大高度(比如 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# : How to resize image proportionately with max height,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10329010/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com