Resize images keeping the aspect ratio in C#

A very useful code snippet which will help you to resize images programmatically in your projects!

There are some moments while developing an application that we have to stop playing with the usual (CRUD) in order to do something that we aren't used to do. One of these things (in my case) is image editing.

The code below is plain simple and the few comments in it might give you an insight of what is happening. Apart from that, the only hard work you will have is to copy the code and paste into your app. Then you only need to make the proper call and, voilà! Resized image without changing the ratio!!

 

public static void ResizeImage(string originalFile, string newFile, int newWidth, int maxHeight, bool onlyResizeIfWider)
{
	Image fullsizeImage = Image.FromFile(originalFile);
 
	// Prevent using images internal thumbnail
	fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
	fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
 
	if (onlyResizeIfWider)
	{
		if (fullsizeImage.Width <= newWidth)
		{
			newWidth = fullsizeImage.Width;
		}
	}
 
	int newHeight = fullsizeImage.Height * newWidth / fullsizeImage.Width;
	if (newHeight > maxHeight)
	{
		// Resize with height instead
		newWidth = fullsizeImage.Width * maxHeight / fullsizeImage.Height;
		newHeight = maxHeight;
	}
 
	Image newImage = fullsizeImage.GetThumbnailImage(newWidth, newHeight, nullIntPtr.Zero);
 
	// Clear handle to original file so that we can overwrite it if necessary
	fullsizeImage.Dispose();
 
	// Save resized picture
	newImage.Save(newFile);
}

Only remember to save the images in a folder with the proper permissions (read/write) in order to avoid errors.

via DZone snippets

		public static void ResizeImage(string originalFile, string newFile, int newWidth, int maxHeight, bool onlyResizeIfWider)
		{
			Image fullsizeImage = Image.FromFile(originalFile);
 
			// Prevent using images internal thumbnail
			fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
			fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
 
			if (onlyResizeIfWider)
			{
				if (fullsizeImage.Width <= newWidth)
				{
					newWidth = fullsizeImage.Width;
				}
			}
 
			int newHeight = fullsizeImage.Height * newWidth / fullsizeImage.Width;
			if (newHeight > maxHeight)
			{
				// Resize with height instead
				newWidth = fullsizeImage.Width * maxHeight / fullsizeImage.Height;
				newHeight = maxHeight;
			}
 
			Image newImage = fullsizeImage.GetThumbnailImage(newWidth, newHeight, nullIntPtr.Zero);
 
			// Clear handle to original file so that we can overwrite it if necessary
			fullsizeImage.Dispose();
 
			// Save resized picture
			newImage.Save(newFile);
		}