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 System.Drawing.Image ResizeImage(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 new size is larger than original the keep original size
    if (max_size > image.Height && max_size > image.Width)
    {
        newHeight = image.Height;
        newWidth = image.Width;
    }
    else 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, newWidth, newHeight);
 
    return thumbnail;
}

Comments are closed.