DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Scale Image To Desired Sizes Keeping Aspect Ratio

10.20.2006
| 8367 views |
  • submit to reddit
        // Scale Image to desired sizes keeping aspect ratio
// Posted @ http://www.thescripts.com/forum/thread225328.html by Noah Coad [MVP .NET/C#]
private Image ScaleImage(Image source, int MaxWidth, int MaxHeight)
{
float MaxRatio = MaxWidth / (float) MaxHeight;
float ImgRatio = source.Width / (float) source.Height;

if (source.Width > MaxWidth)
return new Bitmap(source, new Size(MaxWidth, (int) Math.Round(MaxWidth /
ImgRatio, 0)));

if (source.Height > MaxHeight)
return new Bitmap(source, new Size((int) Math.Round(MaxWidth * ImgRatio,
0), MaxHeight));

return source;
}