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 numbers and uppercase letters in English         protected void  Page_Load (Object sender, eventargs e)         {             Bitmap bitmap = new  Bitmap (100, 25);//Create a bitmap, Width 100, height 25, that's what I call the first part, the rectangle background              graphics&nBsp;g = graphics.fromimage (bitmap);//Create Canvas              g.clear (Color.yellowgreen);//fill the canvas with yellowish green              font font1 = new font ("Arial",  15);//Set font type and size               brush brush = new solidbrush ( Color.Blue);//Set Brush color             pen mypen  = new pen (color.blue, 5);//Create a Brush object              stringbuilder random = new stringbuilder (5);  //creates a mutable string object, Used to store a randomly generated verification code             random rd =  new random ();//create a random number generator object              for  (int i = 0; I < random. capacity; i++)             {                 random. Append (constant[rd. Next (62)]);//Generate a random word multibyte into the random             }             g.drawstring (random. ToString (),  font1, brush, 10, 5);//Draw a string on the canvas              system.io.memorystream ms = new system.io.memorystream ();// Create a data flow memorystream            bitmap. Save (ms, system.drawing.imaging.imageformat.gif);//The output format of the specified image is gif             response.clearcontent ();             response.contenttype =  "Image/gif";             Response.BinaryWrite (Ms. ToArray ());//output binary data stream         }

The effect of the build is this:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/42/31/wKiom1PXFVuBZu-6AAAS84ozNS4701.jpg "title=" Qq20140729101935.jpg "alt=" Wkiom1pxfvubzu-6aaas84ozns4701.jpg "/>

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 numbers and uppercase letters in English         protected void  Page_Load (Object sender, eventargs e)         {             Bitmap bitmap = new  Bitmap (100, 25);//Create a bitmap, Width 100, height 25, that's what I call the first part, the rectangle background              graphics&nBsp;g = graphics.fromimage (bitmap);//Create Canvas              g.clear (Color.yellowgreen);//fill the canvas with yellowish green              font font1 = new font ("Arial",  15);//Set font type and size               float angle = 60;//a basic angle of rotation              float length = 0;//displays the base position of the character, Look Back             brush brush = new  solidbrush (Color.Blue);//Set Paint brush color              Pen mypen = new pen (color.blue, 5);//Create a Brush object              stringbuilder random = new stringbuilder (5);  // Create a mutable string object to hold a randomly generated captcha  &nbsP;          random rd = new random ();// Create a random Number generator object             for  (int i  = 0; i < random. capacity; i++)             {                 random. Append (constant[rd. Next (62)]);//Generate a random word multibyte into the random                  g.resettransform ();//Reset the canvas to the matrix                  sizef size = g.measurestring (Random[random. LENGTH&NBSP;-&NBSP;1]. ToString (),  font1);//Gets the size of the newly generated characters                  g.translatetransform (length + size. width / 2,&Nbsp;size. HEIGHT&NBSP;/&NBSP;2);//Select the center position of this rotation                  g.rotatetransform ((float) Rd. Nextdouble ()  * angle * 2 - angle);//random angle rotation                  g.drawstring (Random[random. LENGTH&NBSP;-&NBSP;1]. ToString (),  font1, brush, new pointf (-size. Width / 2, -size. HEIGHT&NBSP;/&NBSP;2);///Note that this is not the previous example, a one-time drawing of 5 characters, but a painting                  length += size. width;//guarantees that the next stooped will not overwrite the previous character             }             System.IO.MemoryStream ms =  New system.io.memorystream ();//Create a data flow memorystream            &nBsp;bitmap. Save (ms, system.drawing.imaging.imageformat.gif);//The output format of the specified image is gif             response.clearcontent ();             Response.ContentType =  "Image/gif";             response.binarywrite (Ms. ToArray ());//output binary data stream         }

The resulting effect is this:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/42/31/wKioL1PXFp-Q8odMAAAlOjRK5xA334.jpg "title=" Qq20140729104000.jpg "alt=" Wkiol1pxfp-q8odmaaalojrk5xa334.jpg "/>

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.

This article is from the "Give Me a Gener cigarette" blog, please be sure to keep this source http://zhouhongyu1989.blog.51cto.com/2931598/1532047

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.