Home > Backend Development > C++ > How to Proportionally Resize Images While Maintaining Maximum Width and Height?

How to Proportionally Resize Images While Maintaining Maximum Width and Height?

DDD
Release: 2025-01-06 15:30:40
Original
204 people have browsed it

How to Proportionally Resize Images While Maintaining Maximum Width and Height?

Resizing Images Proportionally: Maintaining Maximum Width and Height

In scenarios where images exhibit dimensions surpassing specified maximum limits, it becomes crucial to scale them down proportionally. However, this adjustment requires ensuring that both width and height remain within these constraints. Additionally, the process should adhere to the original aspect ratio.

To accomplish this, a tailored solution is presented:

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;
}
Copy after login

The ScaleImage method meticulously calculates the appropriate scaling factor to proportionately reduce the image without compromising its aspect ratio. It accomplishes this by comparing the provided maximum width and height with the original image dimensions. Once the correct ratio is determined, it is applied to both dimensions to derive the scaled values. A new bitmap is then created with the scaled dimensions, and the original image is drawn onto it proportionally using the graphics context. The resulting image maintains the maximum constraints while preserving its original proportions.

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

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template