Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize an image maintaining the aspect ratio in C#

Tags:

c#

image

I need to know of a way to resize an image to fit in a box without the image stretching too much. The box has set width and height and I want the image to fill as much of the box as possible but maintain the aspect ratio it originally had.

like image 743
John Demetriou Avatar asked Dec 08 '22 06:12

John Demetriou


1 Answers

//calculate the ratio
double dbl = (double)image.Width / (double)image.Height;

//set height of image to boxHeight and check if resulting width is less than boxWidth, 
//else set width of image to boxWidth and calculate new height
if( (int)((double)boxHeight * dbl) <= boxWidth )
{
    resizedImage = new Bitmap(original, (int)((double)boxHeight * dbl), boxHeight);
}
else
{
    resizedImage = new Bitmap(original, boxWidth, (int)((double)boxWidth / dbl) );
}

The formula for scaling with the same ratio is:

newWidth =  (int)((double)boxHeight * dbl)

or

newHeight =  (int)((double)boxWidth / dbl)