Home > Backend Development > C++ > How to Proportionally Resize Images While Maintaining Aspect Ratio with Max Height and Max Width Constraints?

How to Proportionally Resize Images While Maintaining Aspect Ratio with Max Height and Max Width Constraints?

Barbara Streisand
Release: 2025-01-06 14:19:43
Original
891 people have browsed it

How to Proportionally Resize Images While Maintaining Aspect Ratio with Max Height and Max Width Constraints?

Resizing Images Proportionally with MaxHeight and MaxWidth Constraints

Maintaining the aspect ratio of an image is crucial when scaling it to fit specific dimensions. In this scenario, the goal is to resize an image proportionally while adhering to specified maximum height and width constraints.

To achieve this, the image's width and height are compared to the maximum values. If either dimension exceeds its limit, the image is scaled down until both dimensions meet the constraints. However, this scaling must preserve the original aspect ratio to avoid distortion.

One way to accomplish this is through the following code:

public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
    double ratioX = (double)maxWidth / image.Width;
    double ratioY = (double)maxHeight / image.Height;
    double ratio = Math.Min(ratioX, ratioY);

    int newWidth = (int)(image.Width * ratio);
    int newHeight = (int)(image.Height * ratio);

    Bitmap newImage = new Bitmap(newWidth, newHeight);

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

    return newImage;
}
Copy after login

In this code, the width and height ratios (ratioX and ratioY) are calculated to determine how much the image needs to be scaled down. The minimum of these ratios (ratio) ensures that the image is not resized beyond the specified maximum constraints while maintaining its aspect ratio. The new dimensions (newWidth and newHeight) are computed based on the scaling ratio. Finally, a new bitmap (newImage) is created and the original image is drawn onto it with the scaled dimensions.

The above is the detailed content of How to Proportionally Resize Images While Maintaining Aspect Ratio with Max Height and Max Width Constraints?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template