📜  c# resize image keep aspect ratio - C# (1)

📅  最后修改于: 2023-12-03 14:59:40.775000             🧑  作者: Mango

C# - Resize Image and Keep Aspect Ratio

When working with images in C#, it is often necessary to resize them while maintaining the aspect ratio. Calculating the new dimensions and preserving the original proportions can be achieved using mathematical calculations.

Here is an example code snippet that demonstrates how to resize an image while keeping its aspect ratio intact:

public static Image ResizeImage(Image originalImage, int newWidth, int newHeight)
{
    // Calculate the aspect ratio
    float aspectRatio = (float)originalImage.Width / originalImage.Height;

    // Calculate the new dimensions while preserving the aspect ratio
    if (newWidth == 0)
    {
        newWidth = (int)(newHeight * aspectRatio);
    }
    else if (newHeight == 0)
    {
        newHeight = (int)(newWidth / aspectRatio);
    }

    // Create a new bitmap with the new dimensions
    Bitmap resizedImage = new Bitmap(newWidth, newHeight);

    // Create a graphics object to modify the bitmap
    using (Graphics graphics = Graphics.FromImage(resizedImage))
    {
        // Set the interpolation mode to high quality bilinear
        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;

        // Draw the original image on the new bitmap with the new dimensions
        graphics.DrawImage(originalImage, new Rectangle(0, 0, newWidth, newHeight));
    }
    
    // Return the resized image
    return resizedImage;
}

To use this method, you need to pass the original image, desired new width, and desired new height as parameters. The method will return a resized image while maintaining the aspect ratio.

It is important to note that if you pass 0 for either the new width or new height, the method will calculate the appropriate value based on the aspect ratio and the other dimension. This allows you to specify only one dimension and let the method handle the other dimension calculation.

Here is an example usage:

using (Image originalImage = Image.FromFile("original.jpg"))
{
    Image resizedImage = ResizeImage(originalImage, 800, 0);
    resizedImage.Save("resized.jpg", ImageFormat.Jpeg);
}

This example resizes the "original.jpg" image to have a width of 800 pixels while preserving the aspect ratio. The resulting image is saved as "resized.jpg" in JPEG format.

Remember to handle any necessary file IO operations and dispose of the Image and Bitmap objects properly to avoid memory leaks.

I hope this example helps you effectively resize images while maintaining the aspect ratio in your C# projects.