# Resize images while preserving their aspect ratio (ASP.NET)

In Applications sometimes we need to resize images, and one of the challenges is after specifying the new width how to obtain the correct new height or vice versa. we can use the Aspect ratio algorithm to easily calculate that. (Code to Resize image is available below)

NewHeight = GivenWidth * (OriginalHeight / OriginalWidth)

OR

NewWidth = GivenHeight * (OriginalHeight / OriginalWidth)

So basically, first you need to calculate the Aspect ratio of original image (before resizing). and then simply multiply it with the required dimension.

Assuming the original image has a width of 1000 and a height of 1600 and we want it to be resized to a width of 500:

- First find the aspect: (1600 / 1000) = aspect of 1.6
- Now multiply the aspect by the desired new width: 1.6 * 500
- The result of that multiplication is 800, which is what our height should be
- In other words:
800 = 500 * (1600 / 1000)

Full Code if you need to Resize a image in ASP.NET (C#)

private void ResizeImageWithAspect(string fileName, string outputFileName,

int newWidth)

{

Image original = Image.FromFile(fileName);

//Find the aspect ratio between the height and width.

float aspect = (float)original.Height / (float)original.Width;

//Calculate the new height using the aspect ratio

// and the desired new width.

int newHeight = (int)(newWidth * aspect);

//Create a bitmap of the correct size.

Bitmap temp = new Bitmap(newWidth, newHeight, original.PixelFormat);

//Get a Graphics object from the bitmap.

Graphics newImage = Graphics.FromImage(temp);

//Draw the image with the new width/height

newImage.DrawImage(original, 0, 0, newWidth, newHeight);

//Save the bitmap

temp.Save(@"c:\" + outputFileName);

//Dispose of our objects.

original.Dispose();

temp.Dispose();

newImage.Dispose();

}

So above we did the following...

1.Create an Image object using the Image.FromFile method.
2.Create a Bitmap object using our Image object’s data as the source
3.Create a Graphics object that will allow us to manipulate the Bitmap
4.Use the Graphics object to draw the image to the bitmap with a different width/height
5.Use the Bitmap object to save the image to disk

Posted by: