When developing a website, generating thumbnails is a very common and practical function. In the past, it could only be achieved with the help of COM components in ASP, but now it can be easily implemented in .NET using the powerful class library of the framework. The complete code is posted below (With detailed notes), refer to some articles on the Internet and .net sdk related content. All four generation methods are used to upload pictures in QQROOM Network Home.
/// <summary>
/// Generate thumbnails
/// </summary>
/// <param name="originalImagePath">Source image path (physical path)</param>
/// <param name="thumbnailPath">Thumbnail path (physical path)</param>
/// <param name="width">Thumbnail width</param>
/// <param name="height">Thumbnail height</param>
/// <param name="mode">How to generate thumbnails</param>
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
Image originalImage = Image.FromFile(originalImagePath);
int width = width;
int height = height;
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
switch (mode)
{
case "HW"://Specify height and width scaling (possibly deformed)
break;
case "W"://Specify width and height in proportion
toheight = originalImage.Height * width/originalImage.Width;
break;
case "H"://Specify height and width in proportion
towidth = originalImage.Width * height/originalImage.Height;
break;
case "Cut"://Specify height and width to cut (without deformation)
if((double)originalImage.Width/(double)originalImage.Height > (double)towidth/(double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height*towidth/toheight;
y = 0;
x = (originalImage.Width - ow)/2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width*height/towidth;
x = 0;
y = (originalImage.Height - oh)/2;
}
break;
default :
break;
}
//Create a new bmp picture
Image bitmap = new System.Drawing.Bitmap(towidth,toheight);
//Create a new drawing board
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//Set high-quality interpolation method
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//Set high quality, low speed to show smoothness
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//Clear the canvas and fill it with a transparent background color
g.Clear(Color.Transparent);
//Draw the specified part of the original image at the specified position and size
g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
new Rectangle(x, y, ow,oh),
GraphicsUnit.Pixel);
try
{
//Save the thumbnail in jpg format
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch(System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
For the key method Graphics.DrawImage, see ms-help://MS.NETFrameworkSDKv1.1.CHS/cpref/html/frlrfsystemdrawinggraphicsclassdrawimagetopic11.htm
http://www.cnblogs.com/jialine/archive/2006/09/15/505459. html