Numbers plus letter verification code and Chinese Character Verification Code

Source: Internet
Author: User
Tags random seed

// Yang Chun
// 2007-10-12
// Generate a verification code (numbers plus letters or Chinese characters)

Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;

Using system. text;
Using system. drawing;
Using system. IO;
Using system. Drawing. imaging;

Public partial class systempages_validatecode: system. web. UI. page
{< br> protected void page_load (Object sender, eventargs e)
{< br> If (! Ispostback)
{< br> // 4-digit Verification Code
// int length = 4;
// string str_validatecode = generatecheckcode (length ); // Add a verification code in English.

String str_validatecode = generatecheckcode (); // Chinese Character Verification Code
// The session used for verification
Session ["validatecode"] = str_validatecode;
Createimage (str_validatecode );
}
}

// Generate random strings with letters and numbers
Private string generatecheckcode (INT length)
{
Int number;
String strcode = string. empty;
// Random Seed
Random random = new random ();
For (INT I = 0; I <length; I ++)
{
// Random integer
Number = random. Next ();
// The characters are generated from 0-9, A-Z, and the corresponding ASCII code is 48-57,65-90
Number = Number % 36;
If (number <10)
{
Number + = 48;
}
Else
{
Number + = 55;
}
Strcode + = (char) Number). tostring ();
}
// Save the string in cookies
Return strcode;
}

// Generate random Chinese character strings
Private string generatecheckcode ()
{
Int number;
String checkcode = string. empty;
System. Random random = new random ();
Encoding GB = encoding. getencoding ("gb2312 ");
// Call the function to generate four random Chinese character codes
Object [] bytes = createregioncode (6 );
// Decodes Chinese Characters Based on the byte array encoded by Chinese Characters
String str1 = GB. getstring (byte []) convert. changetype (Bytes [0], typeof (byte []);
String str2 = GB. getstring (byte []) convert. changetype (Bytes [1], typeof (byte []);
String str3 = GB. getstring (byte []) convert. changetype (Bytes [2], typeof (byte []);
String str4 = GB. getstring (byte []) convert. changetype (Bytes [3], typeof (byte []);
// Output Console
Checkcode = str1 + str2 + str3 + str4;
Return checkcode;
}

// Generate the Encoding
Private Static object [] createregioncode (INT strlength)
{
// Define a string array to store the components of Chinese character encoding
String [] rbase = new string [16] {"0", "1", "2", "3", "4", "5", "6 ", "7", "8", "9", "A", "B", "C", "D", "E", "F "};

Random RND = new random ();

// Define an object array
Object [] bytes = new object [strlength];

/* Generate a hexadecimal byte array containing two elements at a time in each loop, and put it into the bject array.
Each Chinese Character consists of four location codes.
The first element of the byte array is the 1st bits and 2nd bits.
The second element of the byte array is the 3rd bits and 4th bits.
*/
For (INT I = 0; I <strlength; I ++)
{
// Code 1st bits
Int R1 = RND. Next (11, 14 );
String str_r1 = rbase [R1]. Trim ();

// Code 2nd bits
RND = new random (R1 * unchecked (INT) datetime. Now. ticks) + I); // Replace

// seed to avoid repeated values
int R2;
If (r1 = 13)
{< br> r2 = RND. next (0, 7);
}< br> else
{< br> r2 = RND. next (0, 16);
}< br> string str_r2 = rbase [R2]. trim ();

// Code 3rd bits
RND = new random (R2 * unchecked (INT) datetime. Now. ticks) + I );
Int R3 = RND. Next (10, 16 );
String str_r3 = rbase [R3]. Trim ();

// Code 4th bits
RND = new random (R3 * unchecked (INT) datetime. Now. ticks) + I );
Int R4;
If (R3 = 10)
{
R4 = RND. Next (1, 16 );
}
Else if (R3 = 15)
{
R4 = RND. Next (0, 15 );
}
Else
{
R4 = RND. Next (0, 16 );
}
String str_r4 = rbase [R4]. Trim ();

// Define the random Chinese character location code generated by storing two byte Variables
Byte byte1 = convert. tobyte (str_r1 + str_r2, 16 );
Byte byte2 = convert. tobyte (str_r3 + str_r4, 16 );
// Store two byte variables in the byte array
Byte [] str_r = new byte [] {byte1, byte2 };

// Put the byte array of the generated Chinese character into the object Array
Bytes. setvalue (str_r, I );
}
Return bytes;
}

// Generate random colors
Public color getrandomcolor ()
{
Random randomnum_first = new random (INT) datetime. Now. ticks );
System. Threading. thread. Sleep (randomnum_first.next (50 ));
Random randomnum_sencond = new random (INT) datetime. Now. ticks );

// Generate a dark int int_red = randomnum_first.next (256) as much as possible to display on a white background );
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 );
}
// Create an image
Public void createimage (string str_validatecode)
{
Int int_imagewidth = str_validatecode.length * 15;
Random newrandom = new random ();
// The bitmap object with a height of 20 PX is used to process the image defined by pixel data. Bitmap thebitmap = new Bitmap (int_imagewidth, 20 );
// Graphics. fromimage creates a new graphics object.
Graphics thegraphics = graphics. fromimage (thebitmap );
// White background
Thegraphics. Clear (color. White );
// The gray border thegraphics. drawrectangle draws a rectangular pen (paint color and paint width)
// Drawrectangle (paint brush, X, Y, width, heigth) thegraphics. drawrectangle (new pen (color. lightgray, 1), 0, 0, int_imagewidth-1, 19 );

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

For (INT int_index = 0; int_index <str_validatecode.length; int_index ++)
{
// Substring (1, J) the string str_char = str_validatecode.substring (int_index, 1) with a length of J is obtained from I );
// Call the random return color method brush newbrush = new solidbrush (getrandomcolor ());
// Point (I, j) I horizontal position of the point. The vertical position of the Point J is point thepos = new point (int_index * 14 + 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); // save to the specified stream in the specified format

Response. clearcontent (); // You Need to output the image information to modify the HTTP header.
Response. contenttype = "image/PNG ";
Response. binarywrite (Ms. toarray (); // write a binary string to the HTTP output stream thegraphics. Dispose (); // release all resources used by this graphics object. Thebitmap. Dispose ();
Response. End ();
}

}

Source code:/files/88223100/checkcode.rar

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.