Generating thumbnails is a common and practical function during website development. previously, ASP can only be implemented using COM components. net can be easily implemented using the powerful class libraries of the framework. the following post shows the completeCode(With detailed notes ).
/// <Summary>
/// Generate a thumbnail
/// </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 a thumbnail </param>
Public Static Void Makethumbnail (String Originalimagepath, String Thumbnailpath, Int Width, Int Height, String Mode)
{
Image originalimage = Image. fromfile (originalimagepath );
IntTowidth=Width;
IntToheight=Height;
int x = 0;
int Y = 0;
int ow = originalimage. width;
int oh = originalimage. height;
Switch (Mode)
{
Case "HW" : // Specify high-width Scaling (may be deformed)
Break ;
Case "W" : // Specify the width, and the height is proportional.
Toheight = Originalimage. Height * Width/originalimage. width;
Break ;
Case "H" : // Specify the height. The width is proportional.
Towidth = Originalimage. Width * Height/originalimage. height;
Break ;
Case "Cut" : // Specify the height and width reduction (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 BMP Image
Image bitmap= NewSystem. Drawing. Bitmap (towidth, toheight );
// Create a canvas
Graphics g=System. Drawing. Graphics. fromimage (Bitmap );
// Set a high quality Interpolation Method
G. interpolationmode=System. Drawing. drawing2d. interpolationmode. High;
// Set high quality and smooth Low Speed
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 in the specified size
G. drawimage (originalimage, New rectangle (0, 0, towidth, toheight),
New rectangle (X, Y, ow, oh),
graphicsunit. pixel);
try
{< br> // Save the thumbnail in JPG format
bitmap. save (thumbnailpath, system. drawing. imaging. imageformat. JPEG);
}< br> catch (system. exception e)
{< br> throw E;
}< br> finally
{< br> originalimage. dispose ();
bitmap. dispose ();
G. dispose ();
}< BR >}