Sunday, September 23, 2007

Proportionate Image Scaling with .Net GDI+

Here's the code...

private static Image scaleImage(Image img, int maxHeight, int maxWidth)
{
     int currentHeight = img.Height;
     int currentWidth = img.Width;
     int newHeight = 0;
     int newWidth = 0;

     //prevent enlarging past original height and width
     if (img.Height <= maxHeight && img.Width <= maxWidth)  return img;
     if (currentHeight == 0 || currentWidth == 0)   return img;
     double heightRatio = (double)currentHeight / currentWidth;
     double widthRatio = (double)currentWidth / currentHeight;  newHeight = maxHeight;
     if (widthRatio > 0)
          newWidth = Convert.ToInt32(newHeight * widthRatio);

     if (newWidth > maxWidth)
     {
          newWidth = maxWidth;
          newHeight = Convert.ToInt32(newWidth * heightRatio);
     }

     using (Bitmap scaledImage = new Bitmap(newWidth, newHeight))
     using (Graphics g = Graphics.FromImage(scaledImage))
     {
          g.InterpolationMode = InterpolationMode.HighQualityBicubic;
          foreach (PropertyItem prop in img.PropertyItems)
          scaledImage.SetPropertyItem(prop);
          g.DrawImage(img, 0, 0, newWidth, newHeight);

          return scaledImage;
     }
}

0 comments: