Home
Manage Your Code
Snippet: Resize an image to a max height or width (C#)
Title: Resize an image to a max height or width Language: C#
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. Views: 507
Author: Aaron Crandall Date Added: 8/27/2007
Copy Code  
1const int maxsize = 100;
2
3using(Image image = Bitmap.FromFile(@"C:\image.jpg"))
4{
5	double coeff;
6	if (image.Width > image.Height)
7	{
8		coeff = maxsize/(double) image.Width;
9	}
10	else
11	{
12		coeff = maxsize/(double) image.Height;
13	}
14
15	int newHeight = Convert.ToInt32(coeff*image.Height);
16	int newWidth = Convert.ToInt32(coeff*image.Width);
17	
18	using(Bitmap bitmap = new Bitmap(image, newWidth, newHeight))
19	{
20		bitmap.Save(@"C:\image_resized.jpg", image.RawFormat);
21	}
22}