使用 MaxHeight 和 MaxWidth 约束按比例调整图像大小 [英] Resize image proportionally with MaxHeight and MaxWidth constraints

查看:28
本文介绍了使用 MaxHeight 和 MaxWidth 约束按比例调整图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用System.Drawing.Image.

如果图像宽度或高度超过最大值,则需要按比例调整大小.调整大小后需要确保宽度和高度都不超过限制.

If an image width or height exceed the maximum, it need to be resized proportionally . After resized it need to make sure that neither width or height still exceed the limit.

宽度和高度将自动调整直到不超过最大值和最小值(可能的最大尺寸)并保持比例.

The Width and Height will be resized until it is not exceed to maximum and minimum automatically (biggest size possible) and also maintain the ratio.

推荐答案

喜欢这个吗?

public static void Test()
{
    using (var image = Image.FromFile(@"c:logo.png"))
    using (var newImage = ScaleImage(image, 300, 400))
    {
        newImage.Save(@"c:	est.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);

    using (var graphics = Graphics.FromImage(newImage))
        graphics.DrawImage(image, 0, 0, newWidth, newHeight);

    return newImage;
}

这篇关于使用 MaxHeight 和 MaxWidth 约束按比例调整图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆