ASP. NET implementation Image Processing

Source: Internet
Author: User
Tags bmp image sendfile
Implement a verification code mixed with numbers and characters in ASP. NET
Http://dev.csdn.net/develop/article/22/22618.shtm
First, I want to briefly talk about the usage of Session and ViewState, because it will be used later.
Store data in the Session: Session ("key") = "test"
Value from Session: dim testvalue as string = Session ("key ")
Similar:
Store data in ViewState: ViewState ("key") = "test"
Value From ViewState: dim testvalue as string = ViewState ("key ")
For more information about ViewState, see <ASP. NET ViewState> In MSDN.
Sometimes the Code itself is more expressive than any explanation, so there is not much explanation for the code here. The Verification Code implemented in this article requires two files:
Gif. aspx this file is used to generate a verification code
ValidateCode. aspx this file is used to test the verification code (that is, how to use it)
The complete gif. aspx code is provided below:
<% @ Import namespace = "System" %>
<% @ Import namespace = "System. io" %>
<% @ Import namespace = "System. Drawing" %>
<% @ Import namespace = "System. Drawing. Imaging" %>
<Script language = "vb" runat = "server">
Sub Page_Load (Sender as object, e as eventargs)
'Rndnum is a UDF.
Dim VNum as string = RndNum (4)
Session ("VNum") = VNum
ValidateCode (VNum)
End Sub
'Image verification code generation function
Sub ValidateCode (VNum)
Dim Img as System. Drawing. Bitmap
Dim g as Graphics
Dim MS as MemoryStream
Dim gheight as integer = Int (Len (VNum) * 11.5)
'Gheight indicates the image width. The image width is automatically changed based on the Character length.
Img = new BitMap (Gheight, 20)
G = Graphics. FromImage (img)
G. drawString (VNum, (New Font ("Arial", 10), (New SolidBrush (color. blue), 3, 3) 'draw the string (string, Font, paint color, top left x in the rectangle. y on the top left)
MS = New MemoryStream ()
Img. Save (MS, ImageFormat. Png)
Response. ClearContent () 'needs to output image information to modify the HTTP Header
Response. ContentType = "image/Png"
Response. BinaryWrite (ms. ToArray ())
G. Dispose ()
Img. Dispose ()
Response. End ()
End Sub
'--------------------------------------------
'Function name: RndNum
'Function parameter: VcodeNum -- set the number of digits of the returned random string
'Function: generate a random string mixed with numbers and characters
Function RndNum (VcodeNum)
Dim Vchar as string = ", A, B, C, D, E, F, G, H, I, J, K, L, m, N, O, P, Q, R, S, T, U, W, X, Y, Z"
Dim VcArray () as string = split (Vchar, ",") 'generates an array of strings
Dim VNum as string = ""
Dim I as byte
For I = 1 to VcodeNum
Randomize
VNum = VNum & VcArray (Int (35 * Rnd) 'array is generally read from 0, so here it is 35 * Rnd
Next
Return VNum
End Function
</Script>
The following code shows how to use the image verification code generated by the file:
<Asp: Image id = "Image1" runat = "server" ImageUrl = "gif. aspx"/>
This is the Image control used to display the verification code. You can place it wherever you like. The following provides detailed code for use. You can save it as ValidateCode. aspx and associate it with gif. put aspx in the same directory and open ValidateCode in the browser. aspx, you can test its effect:
<Script language = "vb" Runat = "Server">
Sub Page_Load (Sender as object, e as eventargs)
Dim VNum as string = Session ("VNum ")
Session. Abandon ()
ViewState ("VNum") = VNum
End Sub
'The following Event code is used to test the verification code and can be changed as needed.
Sub btnSubmit_click (sender as object, e as eventargs)
'Determine whether the entered verification code is the same as the given Verification Code
If txtValidateCode. text = Cstr (ViewState ("VNum") then
LblShow. text = "<font color = 'red'> tip: Pass verification </font>"
Else
LblShow. text = "The entered verification code is inconsistent with the given verification code"
End If
End Sub
</Script>
<Html>
<Body>
<Form runat = "server">
<Div align = "center">
& Lt; table width = "750" & gt;
<! -- DWLayoutTable -->
<Tr>
<Td width = "256" height = "46"> & nbsp; </td>
<Td width = "9"> & nbsp; </td>
<Td width = "88"> & nbsp; </td>
<Td width = "87"> & nbsp; </td>
<Td width = "100"> & nbsp; </td>
<Td width = "68"> & nbsp; </td>
<Td width = "97"> & nbsp; </td>
</Tr>
<Tr>
<Td height = "21"> </td>
<Td> </td>
<Td colspan = "3" valign = "top"> <asp: label ID = "lblShow" runat = "server"> </asp: label> </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
</Tr>
<Tr>
<Td height = "14"> </td>
<Td> </td>
<Td> </td>
<Td> </td>
<Td> </td>
<Td> </td>
<Td> </td>
</Tr>
<Tr>
<Td height = "21"> & nbsp; </td>
<Td colspan = "2" valign = "middle"> Verification Code: </td>
<Td valign = "top"> <asp: Image id = "Image1" runat = "server" ImageUrl = "gif. aspx"/> </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
</Tr>
<Tr>
<Td height = "20"> & nbsp; </td>
<Td colspan = "2" valign = "top"> enter the verification code: </td>
<Td valign = "top"> <asp: textbox ID = "txtValidateCode" runat = "server" TextMode = "SingleLine"/> </td>
<Td colspan = "2" valign = "middle"> <font color = "# FF0000" size = "2"> * Note: Case Sensitive </font> </td>
<Td> & nbsp; </td>
</Tr>
<Tr>
<Td height = "25"> & nbsp; </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
</Tr>
<Tr>
<Td height = "19"> & nbsp; </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
<Td valign = "top"> <asp: button ID = "btnSubmit" runat = "server" Text = "Compare" onclick = "btnSubmit_click"/> </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
<Td> & nbsp; </td>
</Tr>
</Table>
</Div>
</Form>
</Body>
</Html>

Http://www.cnblogs.com/thcjp/archive/2006/07/06/444342.html
When using ASP, we often need to use third-party controls to implement some image functions. Now, with the release of ASP. NET, we do not need to use third-party controls to implement them, because ASP. NET already has powerful functions to implement some image processing. Now let's take a look at how to use this powerful feature of ASP. NET.

1. Use of System. Drawing

The following example shows how to generate an image in the memory and then display the image on the webpage. We need to know that what we output here is not the HTML effect, but a real image. We can use "Save ..." Save the output image.

Let's take a look at the effect:

 
We can see that this image is a gradient with the words "have you seen it?". Of course, this effect is easy to implement in PhotoShop and other image processing software. However, some applications combined with databases cannot be designed in advance for all images. At this time, ASP is used. NET. Let's look at the source code:

<%@ page language="vb" contenttype="image/jpeg" %>
<%@ import namespace="system.drawing" %>
<%@ import namespace="system.drawing.imaging" %>
<%@ import namespace="system.drawing.drawing2d" %>

<%
'Clear Response
Response. clear

'Create a 24-bit BMP image of 120*30;
Dim imgOutput as New bitmap (120, 30, pixelformat. format24bpprgb)

'Create a new image based on the above BMP;
Dim g as graphics = graphics. fromimage (imgOutput)

g.clear(color.Green)
g.smoothingMode = smoothingMode.antiAlias

G. drawString ("have you seen it? ", New font (" ", 16, fontstyle. bold), new SolidBrush (Color. White), New pointF (2, 4 ))

g.FillRectangle(New linearGradientBrush(New point(0,0), New point(120,30), color.fromArgb(0,0,0,0),color.fromArgb(255,255,255,255)),0,0,120,30)

imgOutput.save(response.outputstream, imageformat.jpeg)

g.dispose()
imgOutput.dispose()
response.end
%>

In the above code, we can see that, unlike the database program, the image processing namespace system. drawing is introduced here. The program first clears Response to ensure there is no output; then, the program creates a 120 × 30 BMP image, and then creates a new image based on this, after the image is created, first, we will draw a string "have you seen it?". The string is a 16-character bold string with the white color and the position is (2, 4). Finally, we will implement the gradient effect.

The above example is very simple, but if combined with the database, we can achieve a lot of effects that may not be imagined by Using ASP.
Ii. Reading and changing the image file size

Reading images? Can I simply use HTML? Of course we can. Here we only provide a choice and method to implement this function. We may need to learn more about the use of this function in practice. Let's first look at the source code of the program:

<% ' import all relevant namespaces %>
<%@ import namespace="System" %>
<%@ import namespace="System.Drawing" %>
<%@ import namespace="System.Drawing.Imaging" %>
<%@ import namespace="System.IO" %>

<script runat="server">
Sub sendFile()
dim g as System.Drawing.Image = System.Drawing.Image.FromFile(server.mappath(request("src")))
dim thisFormat=g.rawformat
dim imgOutput as New Bitmap(g, cint(request("width")), cint(request("height")))
if thisformat.equals(system.drawing.imaging.imageformat.Gif) then
response.contenttype="image/gif"
else
response.contenttype="image/jpeg"
end if
imgOutput.save(response.outputstream, thisformat)
g.dispose()
imgOutput.dispose()
end sub

Sub sendError ()
Dim imgOutput as New bitmap (120,120, pixelformat. format24bpprgb)
Dim g as graphics = graphics. fromimage (imgOutput)
G. clear (color. yellow)
G. drawString ("error! ", New font (" ", 14, fontstyle. bold), systembrushes. windowtext, New pointF (2, 2 ))
Response. contenttype = "image/gif"
ImgOutput. save (response. outputstream, imageformat.gif)
G. dispose ()
ImgOutput. dispose ()
End sub
</Script>

<%
response.clear
if request("src")="" or request("height")="" or request("width")="" then
call sendError()
else
if file.exists(server.mappath(request("src"))) then
call sendFile()
else
call sendError()
end if
end if
response.end
%>

In the above program, we can see two functions, one is SendFile. This function is mainly used to display images on the server. The image size is set through Width and Height. At the same time, the program will automatically detect the image type; the other is SendError. The main function of this function is to display the error message when the image file on the server does not exist. This is very interesting, the error message is also given through the image ():

The above program shows the image and changes the image size. Now, we will further display the image and keep the length and width ratio of the image. In this way, it may be close to the actual application, this is especially useful when you need to create an electronic album or an image website. Let's take a look at the main functions:

Function NewthumbSize(currentwidth, currentheight)
dim tempMultiplier as Double
if currentheight > currentwidth then
tempMultiplier = 200 / currentheight
Else
tempMultiplier = 200 / currentwidth
end if
dim NewSize as New Size(CInt(currentwidth * tempMultiplier), CInt(currentheight * tempMultiplier))
return NewSize
End Function


The above program is an added function NewthumbSize, which is used to change the image size for a moment. The image length and width are the same as the original image length and width. For other parts, see the above program code.
3. Graphic Effects

If you only display images on the web page, it is easy. Now, let's take a closer look at the powerful functions of ASP. NET. We will learn image inversion, image cutting, image stretching and other techniques commonly used in image processing.
Let's take a look at the program effect:

 
Take a closer look, we can find a variety of image processing effects. Now let's look at the program code:

<%@ Page Language="vb" Debug="True" %>
<%@ import namespace="system.drawing" %>
<%@ import namespace="system.drawing.imaging" %>
<%@ import namespace="system.drawing.drawing2d" %>
<%
dim strFilename as string
dim i as System.Drawing.Image
strFilename = server.mappath("./chris-fsck.jpg")

i = System.Drawing.Image.FromFile(strFilename)

dim b as New system.drawing.bitmap(i.width, i.height, pixelformat.format24bpprgb)
dim g as graphics = graphics.fromimage(b)

g.clear(color.blue)

'Rotate the image
I. RotateFlip (System. Drawing. RotateFlipType. Rotate90FlipX)
G. drawimage (I, New point (0, 0 ))
I. RotateFlip (System. Drawing. RotateFlipType. Rotate270FlipY)

g.RotateTransform(10)
g.drawimage(i,New point(0,0))
g.RotateTransform(10)
g.drawimage(i,New point(20,20))
g.RotateTransform(10)
g.drawimage(i,New point(40,40))
g.RotateTransform(10)
g.drawimage(i,New point(40,40))
g.RotateTransform(-40)
g.RotateTransform(90)
g.drawimage(i,New rectangle(100,-400,100,50),New rectangle(20,20,i.width-20,i.height-20),GraphicsUnit.Pixel)
g.RotateTransform(-90)

'Stretch the image
G. drawimage (I, New rectangle (10, 10, 50, 50), New rectangle (20, 20, I. width-20, I. height-20), GraphicsUnit. Pixel)
G. drawimage (I, New rectangle (50,10, 90,50), New rectangle (20,20, I. width-20, I. height-20), GraphicsUnit. Pixel)
G. drawimage (I, New rectangle (110,10, 150,50), New rectangle (20,20, I. width-20, I. height-20), GraphicsUnit. Pixel)

'Cut the image
G. drawimage (I, 50,100, New rectangle (1860,110,), GraphicsUnit. Pixel)
G. drawimage (I, 140,100, New rectangle (1860,110,), GraphicsUnit. Pixel)

'Rotate the image
I. RotateFlip (System. Drawing. RotateFlipType. Rotate180FlipX)
G. drawimage (I, 230,100, New rectangle (180,110, 60,110), GraphicsUnit. Pixel)

response.contenttype="image/jpeg"

b.save(response.outputstream, imageformat.jpeg)

b.dispose()

%>

In the above program, we can see various techniques for image processing. After careful observation, we can know that the rotating image actually uses a RotateFlip method, while cutting and stretching the image, it is implemented by setting different DrawImage parameters.

Iv. Summary

There are many functions that ASP. NET can achieve in image processing. Here we are a simple introduction. More application functions need to be explored and summarized in practice.

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.