Saturday, May 30, 2009

Scale Image to desired sizes keeping aspect ratio

// Scale Image to desired sizes keeping aspect ratio

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;
}

No comments:

Post a Comment