调整图像大小与比例及了maxHeight制约了maxWidth [英] Resize image proportionally with MaxHeight and MaxWidth constraints

查看:296
本文介绍了调整图像大小与比例及了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:\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);

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

    return newImage;
}

这篇关于调整图像大小与比例及了maxHeight制约了maxWidth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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