Over a million developers have joined DZone.

Scale Image To Desired Sizes Keeping Aspect Ratio

DZone's Guide to

Scale Image To Desired Sizes Keeping Aspect Ratio

Free Resource
// 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;

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}