The GenerateThumbnail() C# function resizes pictures for various formats, such as JPEG, PNG and BMP, and maintains their aspect ratio.
Contextual Ads
More C# Resources
Advertisement
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public void GenerateThumbnail(string filePath, string origFileName, string thumbFileName, ImageFormat imgFormat)
{
System.Drawing.Image origImage = System.Drawing.Image.FromFile(filePath + @"\" + origFileName);
float WidthPer, HeightPer;
int NewWidth, NewHeight;
if (origImage.Width > origImage.Height)
{
NewWidth = ThumbnailSize.Width;
WidthPer = (float)ThumbnailSize.Width / origImage.Width;
NewHeight = Convert.ToInt32(origImage.Height * WidthPer);
}
else
{
NewHeight = ThumbnailSize.Height;
HeightPer = (float)ThumbnailSize.Height / origImage.Height;
NewWidth = Convert.ToInt32(origImage.Width * HeightPer);
}
System.Drawing.Image origThumbnail = new Bitmap(NewWidth, NewHeight, origImage.PixelFormat);
Graphics oGraphic = Graphics.FromImage(origThumbnail);
oGraphic.CompositingQuality = CompositingQuality.HighQuality;
oGraphic.SmoothingMode = SmoothingMode.HighQuality;
oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle oRectangle = new Rectangle(0, 0, NewWidth, NewHeight);
oGraphic.DrawImage(origImage, oRectangle);
origThumbnail.Save(filePath + @"\" + thumbFileName, imgFormat);
origImage.Dispose();
}