Friday, April 3, 2009

Custom image resizing in 3.5

Following is the code that resizes the image cleanly with high quality. This code doesn’t use GetThumbnailImage method and hence uses full size image.
public void ResizeImage(double scaleFactor, Stream fromStream, Stream toStream)
var image = Image.FromStream(fromStream);
var newWidth = (int)(image.Width * scaleFactor);
var newHeight = (int)(image.Height * scaleFactor);
var thumbnailBitmap = new Bitmap(newWidth, newHeight);

var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbnailGraph.DrawImage(image, imageRectangle);

thumbnailBitmap.Save(toStream, image.RawFormat);