Skip to content

Instantly share code, notes, and snippets.

@reciosonny
Created December 29, 2016 15:57
Show Gist options
  • Save reciosonny/ab928a28554013f009f1310aae1188a8 to your computer and use it in GitHub Desktop.
Save reciosonny/ab928a28554013f009f1310aae1188a8 to your computer and use it in GitHub Desktop.
Image resizer
/// <summary>
/// Resizes the image for compression
/// </summary>
/// <param name="img"></param>
/// <param name="maxWidth"></param>
/// <param name="maxHeight"></param>
/// <returns></returns>
private static Image ResizeImage(Image img, int maxWidth, int maxHeight) {
if (img.Height < maxHeight && img.Width < maxWidth) return img;
using (img) {
Double xRatio = (double)img.Width / maxWidth;
Double yRatio = (double)img.Height / maxHeight;
Double ratio = Math.Max(xRatio, yRatio);
int nnx = (int)Math.Floor(img.Width / ratio);
int nny = (int)Math.Floor(img.Height / ratio);
Bitmap cpy = new Bitmap(nnx, nny, PixelFormat.Format32bppArgb);
using (Graphics gr = Graphics.FromImage(cpy)) {
gr.Clear(Color.Transparent);
 
// This is said to give best quality when resizing images
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
 
gr.DrawImage(img,
new Rectangle(0, 0, nnx, nny),
new Rectangle(0, 0, img.Width, img.Height),
GraphicsUnit.Pixel);
}
return cpy;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment