Generating thumbnails is a very common and useful feature in web development. Previously used only with COM components in the ASP, it is now easy to implement in. NET the powerful class library of the framework. The following is a complete code (with detailed comments), referring to some articles on the web and the. NET SDK related content. The Qqroom network home picture uploads all 4 kinds of generation way.
///<summary>
///Generate thumbnails
///</summary>
///<param name= "Originalimagepath" > Source map 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 towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = Originalimage.width;
int oh = originalimage.height;
switch (mode)
{
case "HW"://Specify width scaling (possible variants)
break;
case "W"://Specify wide, high proportional
toheight = originalimage.height * width/originalimage.width;
break;
case "H"://Specify high, wide proportional
towidth = originalimage.width * height/originalimage.height;
break;
case "cut":///Specify width trim (not deformed)
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 artboard
Graphics g = System.Drawing.Graphics.FromImage (bitmap);
//Set high quality interpolation method
G.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.High;
//Set of high quality, low speed rendering smooth degree
G.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//Clear the canvas and fill with transparent background color
g.clear (color.transparent);
//At the specified location and draws the specified portion of the original picture at the specified size
G.drawimage (Originalimage, New Rectangle (0, 0, Towidth, toheight),
new Rectangle (x, Y, Ow,oh),
GraphicsUnit.Pixel);
Try
{
//save 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 ();
}
}
Key method Graphics.DrawImage See MS-HELP://MS.NETFRAMEWORKSDKV1.1.CHS/CPREF/HTML/FRLRFSYSTEMDRAWINGGRAPHICSCLASSDRAWIMAGETOPIC11