ASP. NET scales and scales the original image according to the specified size to display the image,

Source: Internet
Author: User

ASP. NET scales and scales the original image according to the specified size to display the image,

There may be many images on the website, such as product images. They may vary in size, and their width and height are not necessarily the same. Some may be very small. If they are placed on a webpage, the layout may be damaged, but if they are forced to display them according to the specified width and height, deformation may occur due to different proportions, resulting in poor display effect, the biggest drawback is that the file size has not changed at all. When the image size is very large, the user must wait for a long time to download the image. What should I do?

Well, the thumbnail is designed here, just like the thumbnail view in Windows. What you see is the image scaled down from the original image at a ratio, in addition, the specified width and height must be specified. (If the image is not filled in, use blank space ). A thumbnail is generated in real time based on the specified size instead of the source image. The advantage is that you can fully control the quality, width, and height of the thumbnail, and the file size is within a reasonable range, save a long wait.

This article will discuss how to generate thumbnails. In addition, it can derive many useful features, such as writing a verification code control by yourself.

1. Understand the requests and streams for images
In general, we use http: // xxx/a. aspx to request a. aspx webpage. After ASP. NET processes a webpage, it sends the content of the webpage back to the browser. A. The content of aspx is generally a text file Stream Containing hypertext tags. No one will doubt this. However, a. aspx can not only return such plain webpage text, but also broadly open it. It can actually return any type of stream data. However, you only need to perform operations on the Response object to change the content of the output stream.
To regard an image file as a binary stream, we try to create a stream object from an image file and write the stream to Response. in OutputStream, the image file is sent to the requested browser. However, the browser must also identify this image file. Therefore, before sending this stream, change Response. ContentType to the MIME type of this image file. After receiving the stream, the browser calls the relevant application and the image is displayed in the browser. The actual address is still the end of aspx.
In this way, we can understand how to send tags to users. For example, write the img mark in a common webpage so that its src points to a. aspx. After obtaining this webpage, the browser processes the content marked by the img and sends a request to a. aspx. This is a. aspx returned as an image stream, and the browser displays the image.

2. Generate a thumbnail

Create a new webform page. It generates a thumbnail stream by accepting input parameters and sends it back to the browser. The cs code is as follows:

 

Using System; using System. drawing; using System. drawing. imaging; namespace Demo. web {public partial class GetThumbnail: System. web. UI. page {protected void Page_Load (object sender, EventArgs e) {Response. clear (); string originalFileName = Server. mapPath (Request. queryString ["imgSrc"]); int thumbnailWidth = Convert. toInt32 (Request. queryString ["width"]); int thumbnailHeight = Convert. toInt32 (Request. Q UeryString ["height"]); System. drawing. image img = System. drawing. image. fromFile (originalFileName); var thisFormat = img. rawFormat; System. drawing. size newSize = GetNewSize (thumbnailWidth, thumbnailHeight, img. width, img. height); var outBmp = new System. drawing. bitmap (thumbnailWidth, thumbnailHeight); var g = System. drawing. graphics. fromImage (outBmp); // you can specify the quality of the canvas. compositingQuality = System. drawi Ng. drawing2D. compositingQuality. highQuality; g. smoothingMode = System. drawing. drawing2D. smoothingMode. highQuality; g. interpolationMode = System. drawing. drawing2D. interpolationMode. highQualityBicubic; g. clear (System. drawing. color. fromArgb (255,249,255,240 ));//. transparent );//. fromArgb (255,249,255,240); g. drawImage (img, new Rectangle (thumbnailWidth-newSize. width)/2, (thumbnailHeight-new Size. height)/2, newSize. width, newSize. height), 0, 0, img. width, img. height, GraphicsUnit. pixel); g. dispose (); if (thisFormat = System. drawing. imaging. imageFormat. gif) {Response. contentType = "image/gif";} else {Response. contentType = "image/jpeg";} // set the compression quality EncoderParameters encoderParams = new EncoderParameters (); long [] quality = new long [1]; quality [0] = 100; encoderParameter encoderPa Ram = new EncoderParameter (System. drawing. imaging. encoder. quality, quality); encoderParams. param [0] = encoderParam; // The ImageCodecInfo object that obtains information about the built-in image decoder. Var arrayICI = System. drawing. imaging. imageCodecInfo. getImageEncoders (); System. drawing. imaging. imageCodecInfo policici = null; for (int fwd = 0; fwd <arrayICI. length; fwd ++) {if (arrayICI [fwd]. formatDescription. equals ("JPEG") {policici = arrayICI [fwd]; break ;}} if (policici! = Null) outBmp. save (Response. outputStream, jpegICI, encoderParams); else outBmp. save (Response. outputStream, img. rawFormat);} private Size GetNewSize (int maxWidth, int maxHeight, int width, int height) {double w = 0.0; double h = 0.0; double sw = Convert. toDouble (width); double sh = Convert. toDouble (height); double mw = Convert. toDouble (maxWidth); double mh = Convert. toDouble (maxHeight); if (sw <mw & sh <mh) {w = sw; h = sh;} else if (sw/sh)> (mw/mh) {w = maxWidth; h = (w * sh)/sw;} else {h = maxHeight; w = (h * sw)/sh ;} return new System. drawing. size (Convert. toInt32 (w), Convert. toInt32 (h ));}}}

 

In the Page_Load event processing function, we first obtain the path of the original file to which the thumbnail is generated, and the width and height of the thumbnail.
Then we set a subfunction GetNewSize to calculate the size of the real Thumbnail (why? Because the width-to-height ratio of the thumbnail is different from that of the original image, the scaled-down image must be scaled down according to the constraints within the specified width and height range of the thumbnail, fill in the background color to fill the blank. In addition, if the source image is smaller than the thumbnail, we will not enlarge it, but output it according to the source image, so the computation is required ).

We have created an Image object from the original Image and obtained its format and other information. We will use it later.

Next, create a BitMap object and create a canvas from the new BitMap object. Set the quality of the paint brush to high, and the staggered mode to a high quality cube. These aim is to use the best quality to depict the thumbnail. Otherwise, the image will not look good if the information is lost after the image is reduced. Then, the original Image object is "painted" on the new canvas with the specified width and height.

Modify Response. ContentType. This step informs the browser of the MIME type of the stream sent back. This content is included in the HTTP Header and sent to the browser.

After the image is drawn, We need to compress it because the bitmap object is large and is not conducive to transmission. Therefore, in the following operations, we set some high-quality Compression Parameters and use the BitMap Save method to Save the image to the Response. OutputStream stream based on the obtained ICI (image encoding and decoder information.

In this way, in the browser's view, the request to the web page is equivalent to a request to an image file, but the image is generated in real time. You only need to pass the parameter to obtain the thumbnail of the image.

3. Use a thumbnail
It is relatively easy to use thumbnails. You only need to attach the fn parameter after the URL to indicate the location of the original file (relative to the root directory), tw thumbnail width, and th thumbnail height, the following briefly shows the scenarios used in Repeater:

&width=300&height=300' />

 

 

The following is a look at the thumbnail effect:

Postscript
The thumbnail generation method described in this article uses the concept of stream and does not touch the file system. Therefore, you can skip the file system permission check in this way and run it correctly. Of course, you can also use a file system. In addition, according to the above concept of stream output, we can draw a lot of examples. For example, the bar code control of NeoDynamic, you will find that the path of the bar code image is actually the page on this page, he cleverly redirects requests to this page to generate image streams based on the determination of several feature parameters, so that no page is added, and the "magic effect" of the file system is not used ", only one DLL is required.
In addition, many people may use this idea to generate a verification code image and create such a control or webpage by themselves. It is better to create custom controls. I believe everyone has this capability.
Finally, it is very helpful to encourage everyone to flip over MSDN. When VS is installed, three of the 7CD versions are the MSDN Library, which contains almost everything you want to know. If you have time, please visit MSDN China. There will be some excellent articles occasionally.

Related Article

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.