Scale an Image in C# Preserving Aspect Ratio

Thumbnail image of Jason Bauer
Jason Bauer
December 29, 2015 (Last Updated: ) | Reading Time: 1 minutes

If you need to change the size of an Image without changing the ratio of X to Y then this function should do what you want.

Function to Scale a Bitmap in C#

The input parameters maxWidth and maxHeight define the largest values that you want to get back out of the image after it has been scaled.

Here's the code:

static Bitmap ScaleImage(Bitmap bmp, int maxWidth, int maxHeight)
    var ratioX = (double)maxWidth / bmp.Width;
    var ratioY = (double)maxHeight / bmp.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(bmp.Width * ratio);
    var newHeight = (int)(bmp.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);

    using(var graphics = Graphics.FromImage(newImage))
        graphics.DrawImage(bmp, 0, 0, newWidth, newHeight);

    return newImage;

Results of Scaling an Image in C#

Here is a test image that we loaded into the scale function.


And here it is after calling for a maxWidth of 5000 and a maxHeight of 200.

image scaled down
image scaled down

You can see that the maxHeight of 200 was obeyed and the image was scaled while maintaining a proper aspect ratio.

Other Image Processing Guides

You may want to check out some of our other Programming Guides in C#.



anuj gupta - 2016-03-13 10:50:18


i want to change the pas word becouse the also chenge the pass word


BugEngineer - 2020-06-21 13:27:40


Thank you very much! I was trying to implement something similar in Java and your algorithm helped to solve my problem.


Atılay Esen - 2020-07-24 08:31:40


I want to convert this picture to reactangle.Is this possible?

Leave a reply

Thank you! Your comment has been successfully submitted. It will be approved as soon as possible.

More from Efundies