Settembre 26th, 2007
Description: Create a thumbnail from an image and save the thumbnail into it’s original image file format
Link: http://www.codekeep.net/snippets/52492b12-d17b-4dcd-acdf-c2c9fcb09f68.aspx
public bool MakeThumbnail(string thumb, string img, int width, int height, bool keepOriginalRatio)
{
System.Drawing.Image fullSizeImg;
try
{
fullSizeImg = new System.Drawing.Bitmap(img);
}
catch (Exception ex)
{
return false;
}
if ((fullSizeImg.Width <= width) && (fullSizeImg.Height <= height))
{
//Smaller or same size as thumbnail so no need to do anything special
try
{
fullSizeImg.Save(thumb);
return true;
}
catch (Exception ex)
{
return false;
}
}
else
{
if (keepOriginalRatio)
{
if (width <= 0)
{
width = height * fullSizeImg.Width / fullSizeImg.Height;
}
else if (height <= 0)
{
height = width * fullSizeImg.Height / fullSizeImg.Width;
}
else
{
float TargetRatio = width / height;
float CurrentRatio = fullSizeImg.Width / fullSizeImg.Height;
if (CurrentRatio > TargetRatio) //We'll scale height
{ height = width / Convert.ToInt16(CurrentRatio); }
else // We'll scale width
{ width = height * Convert.ToInt16(CurrentRatio); }
}
}
System.Drawing.Image thumbNailImg = new System.Drawing.Bitmap(fullSizeImg, width, height);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(thumbNailImg);
g.FillRectangle(System.Drawing.Brushes.White, 0, 0, width, height);
g.DrawImage(fullSizeImg, 0, 0, width, height);
try
{
thumbNailImg.Save(thumb, fullSizeImg.RawFormat);
}
catch (Exception ex)
{
return false;
}
}
return false;
}