Friday, April 2, 2010

High Quality Image Thumbnails in C#

Why it Happens?

Image formats like jpeg may store the thumbnail inside the same file. If we use System.Drawing.Bitmap method GetThumbnailImage, method checks if there's a thumbnail image stored into the file and, if the thumb is found, it returns that thumbnail version scaled to the width and height you requested. If the thumbnail version of the image is smaller then the size you requested to produce, thats when problem occurs. The thumbnails produced become pixelated as we know stretching an image to a larger once reduces the Image Quality.

Solution

First of all you will need to include the reference of following namespaces

using System.Drawing;
using System.Drawing.Design;


Use the following code to create High Quality Thumbnail/Resize the image.

string originalFilePath = "C:\\originalimage.jpg"; //Replace with your image path
string thumbnailFilePath = string.Empty;
 
Size newSize = new Size(120,90); // Thumbnail size (width = 120) (height = 90)
 
using (Bitmap bmp = new Bitmap(originalFilePath))
{
    thumbnailFilePath = "C:\\thumbnail.jpg"; //Change the thumbnail path if you want
 
    using (Bitmap thumb = new Bitmap((System.Drawing.Image)bmp, newSize))
    {
        using (Graphics g = Graphics.FromImage(thumb)) // Create Graphics object from original Image
        {
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
 
            //Set Image codec of JPEG type, the index of JPEG codec is "1"
            System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
 
            //Set the parameters for defining the quality of the thumbnail... here it is set to 100%
            System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
            eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
 
            //Now draw the image on the instance of thumbnail Bitmap object
            g.DrawImage(bmp, new Rectangle(0, 0, thumb.Width, thumb.Height));
 
            thumb.Save(thumbnailFilePath, codec, eParams);
        }
    }
}


--
www.cinehour.com

No comments: