A graphic verification code page written by myself (passed by ASP. net2.0)

Source: Internet
Author: User
Sample Code
Project requirements: You need to add a graphic verification code on the homepage logon interface. You can search for it on the Internet, especially if you find a few items. The main problem is that the width of images generated by most code is not unique, and the page layout is not easy to control. The second problem is that the color is single, and some images are too abstract. It is easy to make a mistake without looking at them carefully. For specific customers, I only need a digital image verification code with fixed length, width, and various colors. I can use the existing code on the Internet to complete it myself. The following is:

The principle is not complex, that is, to use a webpage as a canvas, use various paint brushes, draw numbers in a specific area, and send them back to the client in a specific format (in this example, PNG format, it is displayed as "image" in IE, and the string used for verification is stored in session.

The main code is as follows: // generate a random number string
Public String getrandomnumberstring (INT int_numberlength)
{
String str_number = string. empty;
Random therandomnumber = new random ();

For (INT int_index = 0; int_index <int_numberlength; int_index ++)
Str_number + = therandomnumber. Next (10). tostring ();

Return str_number;
}

Generate random color public color getrandomcolor ()
{
Random randomnum_first = new random (INT) datetime. Now. ticks );
// There is nothing to say about the random number of C #.
System. Threading. thread. Sleep (randomnum_first.next (50 ));
Random randomnum_sencond = new random (INT) datetime. Now. ticks );

// Try to generate a dark color for display on a white background
Int int_red = randomnum_first.next (256 );
Int int_green = randomnum_sencond.next (256 );
Int int_blue = (int_red + int_green> 400 )? 0: 400-int_red-int_green;
Int_blue = (int_blue & gt; 255 )? 255: int_blue;

Return color. fromargb (int_red, int_green, int_blue );
}

Generate the final image public void createimage (string str_validatecode) based on the verification string)
{
Int int_imagewidth = str_validatecode.length * 13;
Random newrandom = new random ();
// The Image Height Is 20px
Bitmap thebitmap = new Bitmap (int_imagewidth, 20 );
Graphics thegraphics = graphics. fromimage (thebitmap );
// White background
Thegraphics. Clear (color. White );
// Gray border
Thegraphics. drawrectangle (new pen (color. lightgray, 1), 0, 0, int_imagewidth-1, 19 );

// 10pt font
Font thefont = new font ("Arial", 10 );

For (INT int_index = 0; int_index <str_validatecode.length; int_index ++)
{
String str_char = str_validatecode.substring (int_index, 1 );
Brush newbrush = new solidbrush (getrandomcolor ());
Point thepos = new point (int_index * 13 + 1 + newrandom. Next (3), 1 + newrandom. Next (3 ));
Thegraphics. drawstring (str_char, thefont, newbrush, thepos );
}

// Send the generated image back to the client
Memorystream MS = new memorystream ();
Thebitmap. Save (MS, imageformat. PNG );

Response. clearcontent (); // You Need to output the image information to modify the HTTP header.
Response. contenttype = "image/PNG ";
Response. binarywrite (Ms. toarray ());
Thegraphics. Dispose ();
Thebitmap. Dispose ();
Response. End ();
}

Finally, call the above Code in page_load.

Private void page_load (Object sender, system. eventargs E)
{
If (! Ispostback)
{
// 4-digit Verification Code
String str_validatecode = getrandomnumberstring (4 );
// The session used for verification
Session ["validatecode"] = str_validatecode;
Createimage (str_validatecode );
}
}

Add an image to the page and change the image path to the relative path of validatecode. aspx.

Enter the following code for verification: If (textbox1.text = session ["validatecode"]. tostring ())
{
Textbox1.text = "correct! ";
}
Else
Textbox1.text = "error! ";

OK. Here is a summary:
Advantages: 1. simple and clear, suitable for simple application
2. User-friendly, fixed image length and width formats
Disadvantages: 1. If the verification code is required for multiple pages, the session will be overwritten by other pages. You can specify the specific session value as the verification value.
2. Currently, only numbers are supported. However, you can change the code in getrandomnumberstring () to implement a random string of the specified character set.
3. The verification code changes after the page is refreshed.

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.