How to use ASP.net to make simple verification code _ practical tips

Source: Internet
Author: User
Tags generator new set

We all know that the verification code is displayed in the form of pictures, and is dynamically generated, so that we need to draw it, it has to mention is GDI + drawing

Popular science, what is GDI +?
GDI + is an advanced version of the Graphics Device Interface (GDI), providing 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 great deal of support for complex tasks such as displaying text with a variety of fonts, sizes, and styles.

The following is the verification code, for the verification code such a picture, I think is composed of two parts, part of the background of the rectangle, the other part is on its alphanumeric combination (sometimes there are Chinese characters, sometimes pure letters or pure numbers, there is no uniform rules, how to choose to see you ~). For the background of the rectangle, we can directly consider it as a canvas, alphanumeric combination? We can use random numbers to spell out a new set of combinations. This whole process we all think about it, let's look at the code below:
To make a statement, I wrote this verification code of 5 characters in length, written in uppercase and lowercase letters + digital 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 of alphanumeric and uppercase letters protected void Page_Load ( Object sender, EventArgs e) {Bitmap Bitmap = new Bitmap (100, 25);//Create a bitmap, Width 100, high 25, that's what I call the first part, the rectangular background Graphics g = Graphics.fromimage (bitmap);//Create Canvas g.clear (color.yellowgreen);//fill the canvas with yellow-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 Brush Object StringBuilder random = new StringBuilder (5); Creates a variable string object for storing randomly generated authentication codes 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 character alphanumeric into random} g.drawstring (random. TostrING (), font1, Brush, 10, 5);//Draw string on canvas System.IO.MemoryStream ms = new System.IO.MemoryStream ();//Create Data stream Memorystre Am 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:

You may find it so easy to identify that it is a bit like a pupil to the verification code we entered when we logged on to the site. 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 of alphanumeric and uppercase letters protected void Page_Load ( Object sender, EventArgs e) {Bitmap Bitmap = new Bitmap (100, 25);//Create a bitmap, Width 100, high 25, that's what I call the first part, the rectangular background graphi CS g = Graphics.fromimage (bitmap);//Create Canvas g.clear (color.yellowgreen);//fill the canvas with yellow-green font font1 = new Font ("Arial" , 15)//Set font type and size float angle = One base angle of 60;//rotation float length = 0;//display character base position, look back Brush Brush = new Solid Brush (Color.Blue)//Set painting brush color Pen mypen = new Pen (Color.Blue, 5);//Create Brush object StringBuilder random = new Stringbuil Der (5); Creates a variable string object for storing randomly generated authentication codes 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 character alphanumeric into random g.resettransform ()//To reset the canvas to the matrix SizeF size = g.measurestring (random[random.l ENGTH-1]. ToString (), font1);//Gets the size g.translatetransform (length + size) of the newly generated character. WIDTH/2, size. HEIGHT/2);//Select the center position of this rotation g.rotatetransform ((float) Rd. Nextdouble () * angle * 2-angle);//Random angle rotation g.drawstring (random[random. LENGTH-1]. ToString (), font1, Brush, New PointF (-size. WIDTH/2,-size. HEIGHT/2); Note that this is not the previous example of a one-time 5-character painting, but a picture of length + = size.
      width;//guarantee that the next reprint position will not overwrite the previous character} System.IO.MemoryStream ms = new System.IO.MemoryStream ();//Create Data stream 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 resulting effect is this:

Does it look more professional? If you still feel dissatisfied, you can see the relevant content of GDI +, by adding some noise elements, or delete the line such things to improve the difficulty of recognition, I do not enumerate here.
about how to draw the verification code we said, but there are two more questions I'd like to say more.
1, we actually output is a binary stream, how to display to the page and other elements of the page coexist?
one way to do this is to place the code on a separate Web Forms page, to place a element in another page that needs to display the validation code, and to point its src attribute to the URL of the Captcha page. For example, I wrote a paragraph like this:

Copy Code code as follows:

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

In fact, I am using the general method, but I have also written a separate Web custom control, specially generated verification code to use, but when dragged into the page after the run, it will still be the other elements of the page to cover off, the specific reasons I do not know.

2, the main purpose of the verification code is used to verify the use, so we in the user name, the password is not legitimate, but also to determine whether the current input of the verification code is the same as the verification code on the picture.
I did not write this in the code above, in fact, as long as the final verification code generated randomly, the value in a session to go on it. Then in the judge username, password at the same time to compare this session value is OK. Such as:

Copy Code code as follows:

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

3, how the user did not see this piece of verification code, want to change a piece how to achieve?
You can use the script to reassign the SRC attribute of the IMG element to the URL implementation, of course, the point of trouble can also be implemented using AJAX. We can try it by ourselves.

The above is this article to share the production of verification code all the process, I hope you can enjoy.

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.