Sunday, March 24, 2013

Resize an image in C#

Resizing an image is something that can be very useful, even if you aren't writing a specific application that works mostly with images. I'll post three methods to resize an image, in different ways, all of them useful. All three are really easy to understand and to implement.

Resing an image, regardless of the aspect ratio: this is the easiest, can be useful in some situations. Even though you might want to preserve the aspect ratio most of the time, it's a good thing to have the option of resizing without constraints.
public static Image resize(Image img, int width, int height)
{
    // Resize image with the size from the parameters
    Image bmp = new Bitmap(width, height);
    Graphics g = Graphics.FromImage(bmp);
    // The interpolation mode is optional, you can choose whatever you like
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.DrawImage(img, 0, 0, width, height);
    g.Dispose();
    return bmp;
}

Resizing an image, maintainig the aspect ratio, based on percentage. Been able to resize an image sending only the image and a percentage as parameters is really useful, because sometimes that's all you need.
public static Image resize_percentage(Image img, int percentage)
{
    // Resize the image from the percentage parameter
    // Calculate the new dimensions
    int resizedWidth = (img.Width * percentage / 100);
    int resizedHeight = (img.Height * percentage / 100);
    // Make a new bitmap with the new dimensions
    Image bmp = new Bitmap(resizedWidth, resizedHeight);
    // Create the Graphics object to draw on the image
    Graphics g = Graphics.FromImage(bmp);
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.DrawImage(img, 0, 0, resizedWidth, resizedHeight);
    // Always remember to Dispose!
    g.Dispose();
    return bmp;
}

Resizing an image maintaining the aspect ratio, based on actual dimensions. This is one of the most useful methods you'll use when dealing with images.
public static Image resizeWithAR(Image image, int maxWidth, int maxHeight)
{
    // Calculate the ratio to maintain aspect ratio
    double ratioX = (double)maxWidth / image.Width;
    double ratioY = (double)maxHeight / image.Height;
    double ratio = Math.Min(ratioX, ratioY);

    // Calculate the new dimensions
    int newWidth = (int)(image.Width * ratio);
    int newHeight = (int)(image.Height * ratio);

    // Draw the new image
    Image returnImg = new Bitmap(newWidth, newHeight);
    Graphics g = Graphics.FromImage(returnImg);
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.DrawImage(image, 0, 0, newWidth, newHeight);
    g.Dispose();

    return returnImg;
}

No comments:

Post a Comment

prettyprint