Sunday, January 29, 2006

Generating non-pixelated thumbnail images in .NET

The .NET Framework comes with a large set of image manipulation libraries.  Generating thumbnail images becomes very easy.  But image pixelation, if it were a feature, is turned on by default. :)  Here is the basic code to generate a thumbnail without pixelation.  It's inspired by TheLomex on an ASP.NET forum thread.  I have adapted it to C#.
Bitmap original; // your original image
Size resolution = new Size(150, 150); // size of your thumbnail
Image thumbnail = new Bitmap(original, resolution);
Graphics g = Graphics.FromImage(thumbnail);
// The InterpolationMode was the catalyst to eliminate pixelation.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// I'm not sure whether CompositingQuality or SmoothingMode
// contribute at all to good image resizing. Anyone know?
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(original, new Rectangle(0, 0, thumbnail.Size.Width, thumbnail.Size.Height));
// Thumbnail now contains the resized image, all smoothed out and
// non-pixelated!
To save the image now as a JPEG while controlling the compression vs. quality of the saved file, add this code:
// Prepare for a controlled-quality JPEG export
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
Encoder jpegEncoder = Encoder.Quality;
EncoderParameters jpegEncoderParameters = new EncoderParameters(1);
EncoderParameter jpegEncoderQuality = new EncoderParameter(jpegEncoder, jpegQuality);
jpegEncoderParameters.Param[0] = jpegEncoderQuality;

string thumbnailPath; // some path to save your JPEG to
thumbnail.Save(thumbnailPath, jpegCodec, jpegEncoderParameters);
And never forget to call Image.Dispose on all your images when you're done using them, using either using or a finally block.

1 comment: