Resize an image to a max height or width

Agosto 27th, 2007

Description: Resize an image to be no larger than a specified width and height (for instance to create a thumbnail) while maintaining the aspect ratio.

Link: http://www.codekeep.net/snippets/1741ec47-b966-4892-9e60-5335edf3e9c4.aspx

const int maxsize = 100;

using(Image image = Bitmap.FromFile(@"C:\image.jpg"))
{
	double coeff;
	if (image.Width > image.Height)
	{
		coeff = maxsize/(double) image.Width;
	}
	else
	{
		coeff = maxsize/(double) image.Height;
	}

	int newHeight = Convert.ToInt32(coeff*image.Height);
	int newWidth = Convert.ToInt32(coeff*image.Width);

	using(Bitmap bitmap = new Bitmap(image, newWidth, newHeight))
	{
		bitmap.Save(@"C:\image_resized.jpg", image.RawFormat);
	}
}

  • .NET
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.