Use asp.net to display thumbnails on a Web page

Source: Internet
Author: User
Tags file size file system integer urlencode valid
asp.net| Thumbnail | page | show

There may be many pictures on the website, such as product pictures, and they may be different sizes, width and height are not necessarily the same, some very large some very small. If you put it on a Web page, may damage the layout, but if you force them to appear according to the specified width and height, because the proportions will be distorted, the display is very bad, and the biggest disadvantage is that the file size does not change, when the picture is very large, the user wants to see the picture, Must wait for a long waiting to download pictures, how to do?

OK, here's a thumbnail, just like the thumbnail view in Windows, what you see is a picture that shrinks 1:1 from the original, and meets the specified width and height (blank if the picture fills in). Thumbnail is not the original, but the use of the original image in real time according to the specified size generated, his advantage is that you can fully control the quality of thumbnails, width height, file size within reasonable range, save a long wait.

This article discusses how to generate thumbnails, extrapolate, and can derive a number of uses, such as writing a validation code control yourself.

1, understand the picture of the request and flow
In general, we use http://xxx/a.aspxRequest for a.aspx Web page. Asp. NET after the page is processed, the content of the page is sent back to the browser. A.aspx's content is generally a text file stream containing hypertext tags, which no one would suspect. But a.aspx not only can return this very ordinary page text, it is generalized, it can actually put back any type of stream data. Instead, we just need to manipulate the response object to change the contents of the output stream.
Seeing the image file as a binary stream, we tried to create his stream object from an image file and write the stream to Response.outputstream so that the image file was sent to the requesting browser. But the browser must also recognize that this is an image file, so change the Response.ContentType to the MIME type of the image file before sending the stream. After the browser receives this stream, it invokes the relevant application, and the image is displayed in the browser. Although the actual address is an ASPX end.
So we can understand how to send a tag to a user. For example, write an IMG tag in an ordinary Web page so that his src points to a.aspx. When the browser gets the page, it processes the contents of the IMG tag and makes a request to the a.aspx, which is a.aspx as an image stream, and the browser displays the picture.

2. Generate thumbnail image
With the above technical foundation, we can create an empty ASPX page that he sends back to the browser by accepting incoming parameters and generating a stream of thumbnails.
We create a file called getthumbnail.aspx, which reads as follows:

<%@ Page language= "vb" autoeventwireup= "false" codebehind= "GetThumbnail.aspx.vb" inherits= "_51use". GetThumbnail "%>

This page instruction simply tells the server that the hidden class of this file is _51use. GetThumbnail, and if we don't do anything, this file will eventually output space-time.
Next, let's take a look at how his hidden classes are written, where we use the B language:

Program code:

Public Class GetThumbnail
Inherits System.Web.UI.Page

#Region the code generated by the Web Forms Designer

' This call is required by the Web Forms Designer.
<system.diagnostics.debuggerstepthrough () > Private Sub InitializeComponent ()

End Sub

' NOTE: The following placeholder declarations are required by the Web Forms 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 modify it using the Code Editor.
InitializeComponent ()
End Sub

#End Region

Private Sub Page_Load (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles MyBase.Load
' The user code to place the initialization page here
' Get a few parameters to generate the thumbnail image
' Set a default parameter generation 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, )
            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

' Get the ImageCodecInfo object that contains information about the built-in image codec.
Dim Arrayici () as System.Drawing.Imaging.ImageCodecInfo = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders ()
Dim Jpegici 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 for
End If
Next

If not Jpegici are 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 Integ Er, 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
      &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;W = SW
             h = sh
        elseif (sw/sh) > (mw/mh) Then
 & Nbsp;          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 handler, we first get the path to the original file to generate the thumbnail, and the width height of the thumbnail.
Then a getnewsize is set to calculate the size of the real thumbnail (why do you want to compute it?). Because the width of the thumbnail ratio and the original picture of the width and height than the same, shrinking the picture to ensure that the proportion of the original picture, according to the constraints in the specified thumbnail width and height of the principle, fill the dissatisfaction of the place to fill the gap with the background color. In addition, the original image is smaller than the thumbnail, we do not enlarge, but according to the original output, so the calculation is necessary.

We created his image object from the original images and obtained information about its format, which was later used.

Next, create a new bitmap object, and the artboard is created by the new Bitmap object. Set the quality of the brush is high, staggered mode for high-quality, the purpose is to use the best quality to depict the thumbnail, otherwise the picture after the loss of information lost picture distortion is not good to see. Next, use the specified width and height to "draw" the image object of the original picture on the new artboard.

To modify the Response.ContentType, this step is to tell the browser to send back the MIME type of the stream, which is included in the HTTP header sent to the browser.

The image has been painted well, now we want to compress it, because the bitmap object is very large and is not conducive to transmission. So the following operation, we set some high quality compression parameters, according to the obtained ICI (image codec information), using the bitmap save method to save the picture in the Response.outputstream stream.

So in the browser, the request for the Web page is equivalent to a picture file request, but the picture is generated in real time, just pass the parameters valid, you can get the thumbnail image.

3. Use thumbnail image
Using thumbnails becomes relatively simple, just enclose the URL with the parameter FN to indicate the location of the original file (relative to the root), the TW thumbnail width, the th thumbnail height, and the following to briefly show the scenarios used in repeater:

<asp:repeater id=repwarelist runat= "Server" datasource= "<%# dswarelist-%>" >
<ItemTemplate>
<div class= "Itemcontainer" >
<p>src= '.. /lib/getthumbnail.aspx?fn=<%# Server.URLEncode (configurationsettings.appsettings ("WareImgPath") & Container.DataItem ("Wareimgpath"))%>&tw=120&th=120 'Width= "height=" ></p>
</div>
</ItemTemplate>
</asp:Repeater>


The blue part of the code is the URL to the page request, using <%# Server.URLEncode (configurationsettings.appsettings ("Wareimgpath") & Container.DataItem ("Wareimgpath"))%> statements from the database to obtain the path and filename are appropriately constructed into a valid request path. The work is done.

Here's a look at the effect of the thumbnail:

Postscript
The thumbnail generation method described in this paper uses the concept of flow, and the file system is not a thing, so this way can skip the file system permissions check, absolutely correct operation. Of course, you can also use the file system. In addition, according to the concept of the above stream output, extrapolate, can make a lot of use, such as neodynamic barcode control, you will find that the barcode picture path is actually this page, he cleverly will request this page through a number of feature parameters of the decision to generate picture flow, To achieve without adding any pages, without the "magic effect" of the file system, you need only one DLL to use.
In addition, many people ask to generate a captcha picture, you can also use this idea to do a control of their own, or Web pages. If you can do custom controls better. I believe everyone has this ability.
Finally, it is helpful to advocate that we all go over the MSDN. When installing VS, the 7CD version of three is the MSDN Library, which contains nearly everything you want to know. If you have time, you might as well visit MSDN China, and there will be some excellent articles on it at irregular intervals.



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.