27 October 2011

.NET - Resizing an image

Here's a little piece of C# code that resizes an image of any common type.
It was tested for .jpg, .png, .bmp and .gif.
using System.Drawing;
using System.Drawing.Drawing2D;
...
Image image = Image.FromFile(filePath);
if (image.Width > App.MAX_UPLOAD_IMAGE_SIZE ||
    image.Height > App.MAX_UPLOAD_IMAGE_SIZE) {
  int w = image.Width;
  int h = image.Height;
  if (w > h) {
    w = App.MAX_UPLOAD_IMAGE_SIZE;
    h = image.Height * w / image.Width;
  }
  else {
    w = image.Width * h / image.Height;
    h = App.MAX_UPLOAD_IMAGE_SIZE;
  }
  Bitmap bitmap = new Bitmap(w, h);
  Graphics g = Graphics.FromImage((Image)bitmap);
  g.InterpolationMode = InterpolationMode.HighQualityBilinear;
  g.DrawImage(image, 0, 0, w, h);
  g.Dispose();
  image.Dispose();
  (bitmap as Image).Save(filePath);
}

No comments:

Post a Comment