Crop image maintaining aspect ratio in ASP.NET, C#

Sometimes we need to decrease size of the images by maintaining aspect image ratio. The code give below will produce a new image from source image and new image will look exactly like source image.


Before showing codes I would like to share source image details and generated image details. I was asked to generate 360 x 360 size image by maintaining aspect image ratio.

Now you may be thinking this will squeeze image, no this will ever if you pass bool preserveAspectRatio = true so, this is configurable.

Remember, if image is portrait or landscape, one of the generated image dimension (height or weight) will be 360. If image is of square sized, generated image will always be 360 x 360.


Source Image:

Size: 24.5 KB, Dimensions: 784 x 1242

Generated/Output Image:

Size: 4.13 KB, Dimensions: 227 x 360

Understanding Code

All the used codes are given below and you can customize them according to your requirement. I used a button with name ‘btnUpload’ and when button is clicked it will read an image from disk and produces its compressed image as output.

protected void btnUpload_Click(object sender, EventArgs e)
    System.Drawing.Image original = System.Drawing.Image.FromFile(@"D:\Images\3.jpg");
    System.Drawing.Image resized = ResizeImage(original, new Size(360, 360));
    MemoryStream memStream = new MemoryStream();
    resized.Save(memStream, ImageFormat.Jpeg);

    using (var file = System.Drawing.Image.FromStream(memStream))


public static System.Drawing.Image ResizeImage(System.Drawing.Image image, Size size, bool preserveAspectRatio = true)
    int newWidth;
    int newHeight;
    if (preserveAspectRatio)
        int originalWidth = image.Width;
        int originalHeight = image.Height;
        float percentWidth = (float)size.Width / (float)originalWidth;
        float percentHeight = (float)size.Height / (float)originalHeight;
        float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
        newWidth = (int)(originalWidth * percent);
        newHeight = (int)(originalHeight * percent);
        newWidth = size.Width;
        newHeight = size.Height;
    System.Drawing.Image newImage = new Bitmap(newWidth, newHeight);
    using (Graphics graphicsHandle = Graphics.FromImage(newImage))
        graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
    return newImage;

public class Size
public int Width { get; set; }
public int Height { get; set; }

public Size(int p1, int p2)
    this.Width = p1;
    this.Height = p2;

Hope this helps.


Post a Comment

Popular posts from this blog

Lambda two tables and three tables inner join code samples