For creating thumnail images C# has function in System.Drawing in namespace. System.Drawing.Image class contains GetThubnailImage function which creates thumbnail of an image but use this function wisely to create thubnail which maintains the aspect ratio of image thumbnai. Below is the C# function which creates the thumbnail of an image with maintained aspect ratio.
public static void Create_Thumbnails(int size, string FilePath, string ThumbPath)
{
// create an image object, using the filename we just retrieved
System.Drawing.Image image = System.Drawing.Image.FromFile(FilePath);
try
{
int thumbHeight, thumbWidth;
decimal h = image.Height;
decimal w = image.Width;
if (image.Height > image.Width)
{
thumbHeight = size;
decimal tWidth = (w / h) * thumbHeight;
thumbWidth = Convert.ToInt32(tWidth);
}
else
{
thumbWidth = size;
decimal tHeight = (h / w) * thumbWidth;
thumbHeight = Convert.ToInt32(tHeight);
}
// create the actual thumbnail image
System.Drawing.Image thumbnailImage = image.GetThumbnailImage(thumbWidth, thumbHeight, null, IntPtr.Zero);
image.Dispose();
// put the image into the memory stream
thumbnailImage.Save(ThumbPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex)
{
image.Dispose();
throw ex;
}
}
0 comments:
Post a Comment