Showing posts with label GDI. Show all posts
Showing posts with label GDI. Show all posts

Wednesday, October 24, 2007

How to prevent gifs from rendering grainy using .Net GDI

I recently built a Http Handler for an Asp.net application that needed to generate image thumbnails from different image types on the fly. Sounds easy enough, right?

Well it was a simple task until I tried to generate a thumbnail from a gif. After hours and hours trying to figure out how to improve the resolution I found a great article addressing this particular issue.

The key to this conundrum you ask? Color quantization.

Unfortunately System.Drawing uses a web-safe palette even though just about every gif you've ever seen uses an adaptive palette.

The result:

After implementing Brendan Tompkins Octree-based quantization technique...

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