Monday, July 21, 2008

Thumbnails-Part1

High resolution thumbnails with dynamic width and height

This code will check the image original height and width and accordingly will create the
thumb by setting its suitable thumb height and width. Will give high resolution thumb and
also image will not be blur or squeeze. Name space needed

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

Path - path of original file where located
Width,height - will be supplied as perameter.
Will create new thumbnail on c:\hello.jpg

System.Drawing.Image img = System.Drawing.Image.FromFile(Path);
int srcWidth = img.Width;
int srcHeight = img.Height;
Decimal sizeRatio = ((Decimal)srcHeight / srcWidth);
height = Decimal.ToInt32(sizeRatio * width);
if (height > 250)
height = 250;



Size sz = new Size(width, height);
using (Bitmap bmp = new Bitmap(Path))
{
using (Bitmap bmpThumb = new Bitmap((System.Drawing.Image)bmp, sz))
{
using (Graphics grp = Graphics.FromImage(bmpThumb))
{
grp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
grp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
grp.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];

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

grp.DrawImage(bmp, new Rectangle(0, 0, bmpThumb.Width, bmpThumb.Height));


string strDestPath = "c:\\hello.jpg"; // you can give your path where you want to create file

bmpThumb.Save(strDestPath, codec, eParams);

}
}
}

No comments: