调整图像大小与比例及了maxHeight制约了maxWidth图像、比例、大小、maxWidth

2023-09-02 01:20:20 作者:打小就傲

使用为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;
}