Resize images and keep aspect ratio

I needed to store uploaded images in various sizes. It required using a max size and re-sizing it while keeping the aspect ratio.

The following is the result:

public static System.Drawing.Image ResizedImage(this System.Drawing.Image image, int max_size)
{
    var imageHeight = Convert.ToDouble(image.Height);
    var imageWidth = Convert.ToDouble(image.Width);
 
    // maintaining aspect ratio
    var scaleFactor = 0.0;
    var maxsize = Convert.ToDouble(max_size);
    var newWidth = Convert.ToInt32(imageWidth);
    var newHeight = Convert.ToInt32(imageHeight);
 
    if (imageWidth >= imageHeight)
    {
        scaleFactor = maxsize / imageWidth;
        newHeight = Convert.ToInt32(imageHeight * scaleFactor);
        newWidth = max_size;
    }
    else
    {
        scaleFactor = maxsize / imageHeight;
        newWidth = Convert.ToInt32(imageWidth * scaleFactor);
        newHeight = max_size;
    }
 
    var thumbnail = new System.Drawing.Bitmap(newWidth, newHeight);
    var graphic = System.Drawing.Graphics.FromImage(thumbnail);
 
    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
    graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
 
    graphic.DrawImage(image, 0, 0, max_size, newHeight);
 
    return thumbnail;
}

Comments are closed.