Asp.net generates a Chinese Verification Code

Source: Internet
Author: User

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;

Public partial class member_checkcode: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{
// Call the function to generate four random Chinese character codes
String randomcode = createregioncode (4 );
Session ["validnum"] = randomcode;
This. createimage (randomcode );
}
/**/
/// <Summary>
/// Chinese
/// </Summary>
/// <Param name = "strlength"> </param>
/// <Returns> </returns>
Public String 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 the seed of the random number generator to avoid repeated values.
Int R2;
If (r1 = 13)
R2 = RND. Next (0, 7 );
Else
R2 = RND. Next (0, 16 );
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 );

}

// Obtain the gb2312 encoding page (table)
Encoding GB = encoding. getencoding ("gb2312 ");

// Decodes Chinese Characters Based on the byte array encoded by Chinese Characters
String strresult = "";
For (INT I = 0; I <strlength; I ++)
{
Strresult + = GB. getstring (byte []) convert. changetype (Bytes [I], typeof (byte []);
}

Return strresult;
}

/**/
/// <Summary>
/// Create a random Image
/// </Summary>
/// <Param name = "randomcode"> Random Code </param>
Private void createimage (string randomcode)
{
Int randangle = 30; // random Rotation Angle
Int mapwidth = (INT) (randomcode. length * 28 );
Bitmap map = new Bitmap (mapwidth, 28); // creates an image background.
Graphics graph = graphics. fromimage (MAP );
Graph. Clear (color. aliceblue); // clear the screen and fill in the background.
Graph. drawrectangle (new pen (color. Black, 0), 0, 0, map. Width-1, map. Height-1); // draw a border
// Graph. smoothingmode = system. Drawing. drawing2d. smoothingmode. antialias; // Mode

Random Rand = new random ();
// Generate background noise
Pen blackpen = new pen (color. lightgray, 0 );
For (INT I = 0; I <50; I ++)
{
Int x = Rand. Next (0, map. width );
Int y = Rand. Next (0, map. Height );
Graph. drawrectangle (blackpen, X, Y, 1, 1 );
}

// Rotate the verification code to prevent Machine recognition
Char [] chars = randomcode. tochararray (); // split the string into a single character array
// Text distance
Stringformat format = new stringformat (stringformatflags. noclip );
Format. Alignment = stringalignment. Center;
Format. linealignment = stringalignment. Center;
// Define the color
Color [] C = {color. Black, color. Red, color. darkblue, color. Green, color. Orange, color. Brown, color. darkcyan, color. Purple };
// Define the font
String [] font = {"verdana", "Microsoft sans serif", "Comic Sans MS", "Arial", ""};
For (INT I = 0; I <chars. length; I ++)
{
Int cIndex = Rand. Next (7 );
Int findex = Rand. Next (5 );
Font F = new system. Drawing. Font (font [findex], 13, system. Drawing. fontstyle. Bold); // font style (parameter 2 indicates the font size)
Brush B = new system. Drawing. solidbrush (C [cIndex]);
Point dot = new point (22, 16 );
// Graph. drawstring (Dot. X. tostring (), fontstyle, new solidbrush (color. Black), 10,150); // test the display spacing of X coordinates.
Float angle = Rand. Next (-randangle, randangle); // degrees of Rotation
Graph. translatetransform (Dot. X, Dot. Y); // move the cursor to the specified position
Graph. rotatetransform (angle );
Graph. drawstring (chars [I]. tostring (), F, B, 1, 1, format );
// Graph. drawstring (chars [I]. tostring (), fontstyle, new solidbrush (color. Blue), 1, 1, format );
Graph. rotatetransform (-angle); // go back
Graph. translatetransform (2,-dot. Y); // move the cursor to the specified position
}
// Graph. drawstring (randomcode, fontstyle, new solidbrush (color. Blue), 2, 2); // standard random code

// Generate an image
System. Io. memorystream MS = new system. Io. memorystream ();
Map. Save (MS, system. Drawing. imaging. imageformat. GIF );
Response. clearcontent ();
Response. contenttype = "image/GIF ";
Response. binarywrite (Ms. toarray ());
Graph. Dispose ();
Map. Dispose ();
}

}

Front-end with verification code

<Tr> <TD align = "right"> Verification & nbsp; Certificate & nbsp; Code & nbsp; <SPAN class = "red"> * </span> </TD> <label>
<Input type = "text" name = "txtvalidnum" id = "txtvalidnum" class = "int6"/>
</Label>
<Label onclick = "imgchange ()" style = "cursor: pointer;">
The image Verification Code cannot be seen clearly. Change one. </label> </TD> </tr>

JS judgment

Function imgchange ()
{
Document. getelementbyid ("imgsrc"). src = "checkcode. aspx? "+ New date;
}

Judge at the background where the verification code is used

If (request ["txtvalidnum"]. Trim ()! = Session ["validnum"]. tostring ())
{
_ Gotowebmsg ("Verification code error! ");
Return;
}

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.