Use ASP. NET to display thumbnails on webpages

Source: Internet
Author: User

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
With the above technical foundation, we can establish such an empty aspx webpage, which will generate a thumbnail stream and send it back to the browser by accepting input parameters.
Create a file named GetThumbnail. aspx with the following content:

<% @ Page Language = "vb" AutoEventWireup = "false" Codebehind = "GetThumbnail. aspx. vb" Inherits = "_ 51use. GetThumbnail" %>

This Page command only tells the server that the hidden class of this file is _ 51use. GetThumbnail. If we do not perform any operation, the file will eventually output time and space.
Next, let's take a look at how his hidden classes are written. Here we use the B language:

Program code:

Public Class GetThumbnail
Inherits System. Web. UI. Page

# Region "code generated by Web forms designer"

'The call is required by the Web form designer.
<System. Diagnostics. DebuggerStepThrough ()> Private Sub InitializeComponent ()

End Sub

'Note: The following placeholder declaration is required by the Web form designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System. Object

Private Sub Page_Init (ByVal sender As System. Object, ByVal e As System. EventArgs) Handles MyBase. Init
'Codegen: This method call is required by the Web forms designer
'Do not use the code editor to modify it.
InitializeComponent ()
End Sub

# End Region

Private Sub Page_Load (ByVal sender As System. Object, ByVal e As System. EventArgs) Handles MyBase. Load
'User code to place the initialization page here
'Obtain several parameters to generate a thumbnail.
'Set a default parameter to generate BitMap
Response. Clear ()
Try
Dim originalFileName As String = Server. MapPath (Request ("fn "))
Dim thumbnailWidth As Integer = Request ("tw ")
Dim thumbnailHeight As Integer = Request ("th ")

Dim img As System. Drawing. Image = System. Drawing. Image. FromFile (originalFileName)
Dim thisFormat As System. Drawing. Imaging. ImageFormat = img. RawFormat
Dim newSize As System. Drawing. Size = Me. GetNewSize (thumbnailWidth, thumbnailHeight, img. Width, img. Height)
Dim outBmp As New System. Drawing. Bitmap (thumbnailWidth, thumbnailHeight)
Dim g As System. Drawing. Graphics = System. Drawing. Graphics. FromImage (outBmp)

'Set the painting quality of the canvas.
G. CompositingQuality = Drawing2D. CompositingQuality. HighQuality
G. SmoothingMode = Drawing2D. SmoothingMode. HighQuality
G. InterpolationMode = Drawing2D. InterpolationMode. HighQualityBicubic
G. Clear (system. Drawing. color. fromargb (255,249,255,240 ))
G. drawimage (IMG, new rectangle (thumbnailwidth-newsize. width)/2, (thumbnailheight-newsize. height)/2, newsize. width, newsize. height), 0, 0, IMG. width, IMG. height, graphicsunit. pixel)
G. Dispose ()

If thisformat. Equals (system. Drawing. imaging. imageformat. GIF) then
Response. contenttype = "image/GIF"
Else
Response. ContentType = "image/jpeg"
End If

'Set Compression Quality
Dim encoderParams As New System. Drawing. Imaging. EncoderParameters
Dim quality (0) As Long
Quality (0) = 100
Dim encoderParam As New System. Drawing. Imaging. EncoderParameter (System. Drawing. Imaging. Encoder. Quality, quality)
EncoderParams. Param (0) = encoderParam

'The ImageCodecInfo object that contains information about the built-in image decoder.
Dim arrayICI () As System. Drawing. Imaging. ImageCodecInfo = System. Drawing. Imaging. ImageCodecInfo. GetImageEncoders ()
Dim policici As System. Drawing. Imaging. ImageCodecInfo = Nothing
For fwd As Integer = 0 To arrayICI. Length-1
If arrayICI (fwd). FormatDescription. Equals ("JPEG") Then
JpegICI = arrayICI (fwd)
Exit
End If
Next

If Not specified ICI Is Nothing Then
OutBmp. Save (Response. OutputStream, jpegICI, encoderParams)
Else
OutBmp. Save (Response. OutputStream, thisFormat)
End If
Catch ex As Exception

End Try
End Sub

Function GetNewSize (ByVal maxWidth As Integer, ByVal maxHeight As Integer, ByVal width As Integer, ByVal height As Integer) As System. Drawing. Size
Dim w As Double = 0.0
Dim h As Double = 0.0
Dim sw As Double = Convert. ToDouble (width)
Dim sh As Double = Convert. ToDouble (height)
Dim mw As Double = Convert. ToDouble (maxWidth)
Dim mh As Double = Convert. ToDouble (maxHeight)

If sw <mw And sh <mh Then
W = sw
H = sh
ElseIf (sw/sh)> (mw/mh) Then
W = maxWidth
H = (w * sh)/sw
Else
H = maxHeight
W = (h * sw)/sh
End If
Return New System. Drawing. Size (Convert. ToInt32 (w), Convert. ToInt32 (h ))
End Function
End Class

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:

<Asp: Repeater id = repWareList runat = "server" DataSource = "<% # dsWareList %>">
<ItemTemplate>
<Div class = "ItemContainer">
<P> & tw = 120 & th = 120 'width = "120" height = "120"> </p>
</Div>
</ItemTemplate>
</Asp: Repeater>

The blue part of the code is the URL of the page request, using <% # Server. urlEncode (Configurationsettings. appsetiner ("WareImgPath") & Container. dataItem ("WareImgPath") %> the statement obtains the path from the database and constructs a valid request path based on the file name. The work is complete.

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.

Limited by the author level, making mistakes inevitable. Please criticize and correct me!

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.