Monday, July 21, 2008

Resizing Uploaded Pictures

As tantalizing as it is to use GetThumbnailImage to generate a thumbnail from an uploaded picture, we should not rely on this Bitmap method. Indeed, the uploaded picture may already contain an embedded thumbnail, and GetThumbnailImage will use it if possible. Should the embedded thumbnail be smaller that the one we need, it will be enlarged to ugly results.

Instead, we should use the Graphics class to create our thumbnail from scratch. Still, we should take care not to create a thumbnail larger than the original picture.

Bitmap resizedBitmap = new Bitmap(resizedWidth, resizedHeight, PixelFormat.Format48bppRgb);
Graphics resizedGraphic = Graphics.FromImage(resizedBitmap);
resizedGraphic.CompositingQuality = CompositingQuality.HighQuality;
resizedGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
resizedGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
resizedGraphic.SmoothingMode = SmoothingMode.HighQuality;
resizedGraphic.DrawImage(originalBitmap, 0, 0, resizedWidth, resizedHeight);
resizedGraphic.Dispose();

No comments: