Home >Backend Development >C++ >How to Proportionally Resize Images with MaxHeight and MaxWidth Constraints in C#?

How to Proportionally Resize Images with MaxHeight and MaxWidth Constraints in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-06 13:55:40932browse

How to Proportionally Resize Images with MaxHeight and MaxWidth Constraints in C#?

Resizing Images Proportionally with MaxHeight and MaxWidth Constraints

Maintaining the aspect ratio while resizing images within specified constraints is a common requirement in various applications. Using System.Drawing.Image, you can resize images proportionally while ensuring they stay within the maximum width and height limits.

Problem:

If an image's width or height exceeds the maximum specified, it needs to be resized proportionally. However, after resizing, it's crucial to ensure that neither the width nor height still exceeds the maximum limit. The image should be resized until it fits within the maximum dimensions while maintaining the original aspect ratio.

Solution:

The provided C# code demonstrates how to achieve this:

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;
}

Explanation:

  • The ScaleImage method takes an image, maximum width, and maximum height as parameters.
  • It calculates the ratio of the maximum width and height to the original image's width and height.
  • The minimum ratio value is used to resize the image proportionally.
  • The new width and height are calculated based on the ratio.
  • A Bitmap with the new dimensions is created, and the original image is drawn onto it with the specified dimensions.
  • The resulting proportional resized image is returned.

By using this technique, you can resize images while maintaining their aspect ratio, ensuring they fit within the specified maximum dimensions.

The above is the detailed content of How to Proportionally Resize Images with MaxHeight and MaxWidth Constraints in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn