I recently studied a thumbnail, which is a headache. I 'd like to share the Code with you:
Private void drawimagerectrect (string rawimgpath, string newimgpath, int width, int height)
{
System. Drawing. Image imagefrom = system. Drawing. image. fromfile (rawimgpath );
// Source image width and height
Int imagefromwidth = imagefrom. width;
Int imagefromheight = imagefrom. height;
// Position in the original layout
Int X, Y;
// The length and width obtained in the original layout
Int bitmapwidth, bitmapheight;
/// Calculate the actual size of the thumbnail and its position on the "canvas" based on the source image and the size of the thumbnail to be generated.
If (imagefromwidth/width> imagefromheight/height)
{
Bitmapwidth = (width * imagefromheight)/height;
Bitmapheight = imagefromheight;
X = (imagefromwidth-bitmapwidth)/2;
Y = 0;
}
Else
{
Bitmapwidth = imagefromwidth;
Bitmapheight = (height * imagefromwidth)/width;
X = 0;
Y = (imagefromheight-bitmapheight)/2;
}
// Create a canvas
Bitmap BMP = new Bitmap (width, height );
Graphics G = graphics. fromimage (BMP );
// Clear with white
G. Clear (color. White );
// Specify a high quality double-cubic Interpolation Method. Perform pre-filtering to ensure high-quality shrinkage. This mode produces the highest quality conversion images.
G. interpolationmode = interpolationmode. highqualitybicubic;
// Specify high quality and low-speed rendering.
G. smoothingmode = smoothingmode. highquality;
// Draw the specified part of the specified image at the specified position and in the specified size.
G. drawimage (imagefrom, new rectangle (0, 0, width, height), new rectangle (X, Y, bitmapwidth, bitmapheight), graphicsunit. pixel );
Try
{
// The size and quality of. jpg thumbnails are optimized.
BMP. Save (newimgpath, imageformat. JPEG );
}
Catch
{
}
Finally
{
// Display the resources released
Imagefrom. Dispose ();
BMP. Dispose ();
G. Dispose ();
}
}
Hope to help the comrades.