Image thumbnail generation

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.