smart developer’s blog

This is a C# resource library! Free how to’s and best practices…

Posts Tagged ‘thumbnail

Generate image thumbnails using ASP.NET(C#)

with 7 comments

You can use the GetThumbnailImage built-in method to generate a thumbnail using this method I created:

public static void CreateThumbnail(string ImageFrom, string ImageTo, int ImageHeight)
System.Drawing.Image i = System.Drawing.Image.FromFile(ImageFrom);


System.Drawing.Image th = i.GetThumbnailImage
ImageHeight * i.Width / i.Height,
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),

EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)80);
ImageCodecInfo ici = GetEncoderInfo(“image/jpeg”);

th.Save(ImageTo, ici, ep);

private static ImageCodecInfo GetEncoderInfo(String mimeType)
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for(j = 0; j < encoders.Length; ++j) { if(encoders[j].MimeType == mimeType) return encoders[j]; } return null; } public static bool ThumbnailCallback() { return true; } [/sourcecode] If the Image contains an embedded thumbnail image (all digital cameras attach a thumbnail to the big image), this method retrieves the embedded thumbnail and scales it to the requested size. But the problem is that in most of the cases we do not want this because we want to generate thumbnails bigger than 150-200 pixels as embwdded thumbnails have and this will lead in poor quality images for 400-500 pizels or more thumbnail sizes. The workaround is to use this piece of code: [sourcecode language="csharp"] i.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); i.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); [/sourcecode] By fliping the image twice we get a new image identical with the original one but without the embedded thumbnail. Now the resulted thumbnail is in a very good quality. If you combine this with the cropped image auto-generation you can get a nice method that can generate a cropped thumbnail. 🙂


Written by smartdev

April 9, 2009 at 3:41 pm

Posted in .Net, Programming

Tagged with ,