What is the fastest and more reliable way of generating thumbnails in .NET? I need to get any image, compress it in JPEG and resize it.
I\'ve seen several examples w
This has done me fine for years:
public static void CreateThumbnail(string filename, int desiredWidth, int desiredHeight, string outFilename)
{
using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
{
float widthRatio = (float)img.Width / (float)desiredWidth;
float heightRatio = (float)img.Height / (float)desiredHeight;
// Resize to the greatest ratio
float ratio = heightRatio > widthRatio ? heightRatio : widthRatio;
int newWidth = Convert.ToInt32(Math.Floor((float)img.Width / ratio));
int newHeight = Convert.ToInt32(Math.Floor((float)img.Height / ratio));
using (System.Drawing.Image thumb = img.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailImageAbortCallback), IntPtr.Zero))
{
thumb.Save(outFilename, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
public static bool ThumbnailImageAbortCallback()
{
return true;
}