How to make simple verification code for ASP

Source: Internet
Author: User
Tags new set

If you want to make a verification code, then you have to mention that GDI + drawing. We all know that the CAPTCHA is presented as an image and is dynamically generated, so we need to draw it.

Popular science, what is GDI +?

GDI + is an advanced version of the Graphics Device Interface (GDI) that provides a variety of rich graphics image processing capabilities. GDI + is mainly composed of two-dimensional vector graphics, image processing and layout 3 parts. GDI + provides a lot of support for complex tasks such as displaying text using a variety of fonts, sizes, and styles.

The following is the verification code, for the verification code such as the picture, I think is composed of two parts, part of the background of the rectangle, the other part is on the combination of alphanumeric (sometimes there are Chinese characters, sometimes pure letters or pure numbers, this does not have a unified rule, how to choose to see you ~). For the background of the rectangle, can we just think of it as a canvas, an alphanumeric combination? We can use random numbers to spell out a new set of combinations. So we all think about the whole process, let's look at the code below:

To declare, I wrote this verification code is 5 characters long, by the uppercase and lowercase English letter + number random combination.

        Private ReadOnly Char[] constant = {' 0 ',' 1 ',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ',' 8 ',' 9 ',' A ',' B ',' C ',' d ',' E ',' F ',' G ',' h ',' I ',' J ',' K ',' l ',' m ',' n ',' O ',' P ',' Q ',' R ',' s ',' t ',' u ',' V ',' W ',' x ',' y ',' Z ',' A ',' B ',' C ',' D ',' E ',' F ',' G ',' H ',' I ',' J ',' K ',' L ',' M ',' N ',' O ',' P ',' Q ',' R ',' S ',' T ',' U ',' V ',' W ',' X ',' Y ',' Z '};//A character array consisting of alphanumeric and uppercase letters        protected voidPage_Load (Objectsender, EventArgs e) {Bitmap Bitmap =NewBitmap (100, 25);//Create a bitmap, Width 100, height 25, that's what I'm talking about. The first part, the rectangle backgroundGraphics g = graphics.fromimage (bitmap);//Create canvasG.clear (Color.yellowgreen);//Fill the canvas with yellowish greenFont font1 =NewFont ("Arial", 15);//Set font type and sizeBrush Brush =NewSolidBrush (Color.Blue);//Set paint brush colorPen Mypen =NewPen (Color.Blue, 5);//Create a Brush objectStringBuilder random =NewStringBuilder (5);//Create variable string object to hold randomly generated verification codeRandom rd =NewRandom ();//Create a random number generator object             for(inti = 0; I < random. capacity; i++) {random. Append (constant[rd. Next (62)]);//Generate a random word multibyte into random} g.drawstring (random. ToString (), font1, Brush, 10, 5);//Draw a string on the canvasSystem.IO.MemoryStream ms =NewSystem.IO.MemoryStream ();//Create Data Flow MemoryStreamBitmap. Save (MS, SYSTEM.DRAWING.IMAGING.IMAGEFORMAT.GIF);//Specify the output format of the image as GIFResponse.clearcontent (); Response.ContentType ="Image/gif"; Response.BinaryWrite (Ms. ToArray ());//output binary data stream}

The effect of the build is this:

You may find it so easy to recognize that it is a little bit like a schoolboy when we enter a website with a verification code. Of course, we can make some changes and compare them with a certain angle.

        Private ReadOnly Char[] constant = {' 0 ',' 1 ',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ',' 8 ',' 9 ',' A ',' B ',' C ',' d ',' E ',' F ',' G ',' h ',' I ',' J ',' K ',' l ',' m ',' n ',' O ',' P ',' Q ',' R ',' s ',' t ',' u ',' V ',' W ',' x ',' y ',' Z ',' A ',' B ',' C ',' D ',' E ',' F ',' G ',' H ',' I ',' J ',' K ',' L ',' M ',' N ',' O ',' P ',' Q ',' R ',' S ',' T ',' U ',' V ',' W ',' X ',' Y ',' Z '};//A character array consisting of alphanumeric and uppercase letters        protected voidPage_Load (Objectsender, EventArgs e) {Bitmap Bitmap =NewBitmap (100, 25);//Create a bitmap, Width 100, height 25, that's what I'm talking about. The first part, the rectangle backgroundGraphics g = graphics.fromimage (bitmap);//Create canvasG.clear (Color.yellowgreen);//Fill the canvas with yellowish greenFont font1 =NewFont ("Arial", 15);//Set font type and size            floatangle = 60;//rotation of a base angle            floatlength = 0;//Display the base position of the character, looking backBrush Brush =NewSolidBrush (Color.Blue);//Set paint brush colorPen Mypen =NewPen (Color.Blue, 5);//Create a Brush objectStringBuilder random =NewStringBuilder (5);//Create variable string object to hold randomly generated verification codeRandom rd =NewRandom ();//Create a random number generator object             for(inti = 0; I < random. capacity; i++) {random. Append (constant[rd. Next (62)]);//Generate a random word multibyte into randomG.resettransform ();//Reset the canvas to the matrixSizeF size = g.measurestring (random[random. LENGTH-1]. ToString (), font1);//Get the dimensions of the newly generated charactersG.translatetransform (length + size). WIDTH/2, size. HEIGHT/2);//Select the center position of this rotationG.rotatetransform ((float) Rd. Nextdouble () * angle * 2-angle);//Perform random angle rotationg.DrawString (Random[random. LENGTH-1]. ToString (), font1, Brush,NewPointF (-size. WIDTH/2,-size. HEIGHT/2));//Note, this is not the previous example, the 5 characters are painted all at once, but a pictureLength + = size. Width;//guarantee that the next stooped will not overwrite the previous character} System.IO.MemoryStream ms =NewSystem.IO.MemoryStream ();//Create Data Flow MemoryStreamBitmap. Save (MS, SYSTEM.DRAWING.IMAGING.IMAGEFORMAT.GIF);//Specify the output format of the image as GIFResponse.clearcontent (); Response.ContentType ="Image/gif"; Response.BinaryWrite (Ms. ToArray ());//output binary data stream}

The resulting effect is this:

Does it look more professional? If you still feel dissatisfied, you can look at the relevant content of GDI +, by adding some noise elements, or delete the line so that things to achieve the purpose of improving the recognition difficulty, I do not list here.

about how to draw the verification code we said, but there are two questions I'd like to say more.

1. What we actually output is a binary stream, how do we display it on the page and coexist with other elements of the page?

One way to do this is to put this piece of code in a separate Web Forms page, put a element on another page that needs to display the verification code, and point its src attribute to the URL of the Captcha page. Like I wrote a paragraph like this.

<asp:image id="Image_validatecode" runat= "server" imageurl= "~/publicmethod/ Validatecode.aspx "style="padding-left:3px"/>

In fact, I use a common method here, but I have also previously written a Web custom control, specifically generated code to use, but when dragged into the page after the run, it will still be the page other elements to cover out, the specific reason I am not clear.

2, the main purpose of verification code is used to verify, so we in the user name, password is legitimate, but also to determine whether the current input verification code is consistent with the verification code on the image.

I did not write this in the above code, in fact, as long as the random generation of the final verification code, the value is stored in a session to go to it. Then in the judgment of the user name, password at the same time to compare the session value is OK. Such as:

session["Login_validate_code"] = random. ToString ();

3, How the user did not see this verification code, want to change a how to achieve?

The URL can be re-assigned to the SRC attribute of the IMG element via scripting, but it can be done using AJAX, of course. You can try it on your own.

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.