. NET mixed Chinese and English verification code implementation code

Source: Internet
Author: User

Final Effect

The CheckCode. aspx. cs code is as follows:
Copy codeThe Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
// Obtain the GB2312 encoding page (table)
/**//**
* How to generate a Chinese Verification Code
* Note: when generating a Chinese verification code, you must change the width of the image that generates the verification code.
* Var imageCode = new System. Drawing. Bitmap (int) Math. Ceiling (code. Length * 22.5), 23); // defines the width and height of the image.
**/

// Var gb = Encoding. GetEncoding ("gb2312 ");

/** // Call the function to generate four random Chinese character codes
// Object [] bytes = CreateRegionCode (4 );

/** // Decodes Chinese characters from the byte array encoded by Chinese Characters
// Var sbCode = new StringBuilder (). Append (gb. GetString (byte []) Convert. ChangeType (bytes [0], typeof (byte [])
//. Append (gb. GetString (byte []) Convert. ChangeType (bytes [1], typeof (byte [])
//. Append (gb. GetString (byte []) Convert. ChangeType (bytes [2], typeof (byte [])
//. Append (gb. GetString (byte []) Convert. ChangeType (bytes [3], typeof (byte []);
// CreateCheckCodeImage (sbCode. ToString ());

CreateCheckCodeImage (GenerateCheckCode (); // method used to generate numbers in English
}

Generate a Chinese character Verification Code # region generate a Chinese character Verification Code
/** // <Summary>
/// This function randomly creates a hexadecimal byte array containing two elements within the Chinese character encoding range. Each byte array represents a Chinese character and stores four byte arrays in the object array.
/// </Summary>
/// <Param name = "strLength"> indicates the number of Chinese characters to be generated. </param>
/// <Returns> </returns>
Static object [] CreateRegionCode (int strLength)
{
Var rBase = new []
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9 ", "a", "B", "c", "d", "e", "f"
};

Var random = new Random ();
Var bytes = new object [strLength];

/** // * Generates a hexadecimal byte array containing two elements at a time in each loop, and puts 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
Var r1 = random. Next (11, 14 );
Var str_r1 = rBase [r1]. Trim ();

Random = new Random (r1 * unchecked (int) DateTime. Now. Ticks) + I); // Replace the seed of the random number generator to avoid repeated values.

Var r2 = 0;
If (r1 = 13)
R2 = random. Next (0, 7 );
Else
R2 = random. Next (0, 16 );

Var str_r2 = rBase [r2]. Trim ();

// Code 3rd bits
Random = new Random (r2 * unchecked (int) DateTime. Now. Ticks) + I );
Var r3 = random. Next (10, 16 );
Var str_r3 = rBase [r3]. Trim ();

// Code 4th bits
Random = new Random (r3 * unchecked (int) DateTime. Now. Ticks) + I );
Var r4 = 0;
If (r3 = 10)
R4 = random. Next (1, 16 );
Else if (r3 = 15)
R4 = random. Next (0, 15 );
Else
R4 = random. Next (0, 16 );

Var str_r4 = rBase [r4]. Trim ();

Var byte1 = Convert. ToByte (str_r1 + str_r2, 16 );
Var byte2 = Convert. ToByte (str_r3 + str_r4, 16 );
// Store two byte variables in the byte array
Var str_r = new [] {byte1, byte2 };

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

Generating images # region generating images
Void CreateCheckCodeImage (string code)
{
Var imageCode = new System. Drawing. Bitmap (int) Math. Ceiling (code. Length * 12.5), 23); // defines the width and height of the image.
Var g = Graphics. FromImage (imageCode); // load the image to the canvas

Try
{
Var random = new Random ();
G. Clear (Color. White); // Clear the background Color of the image.

// Draw the background noise line of the image
For (int I = 0; I <25; I ++)
{
Var x1 = random. Next (imageCode. Width );
Var x2 = random. Next (imageCode. Width );
Var y1 = random. Next (imageCode. Height );
Var y2 = random. Next (imageCode. Height );

G. DrawLine (new Pen (Color. Silver), new Point (x1, y1), new Point (x2, y2 ));
}

Var font = new System. Drawing. Font ("Arial", 12F, System. Drawing. FontStyle. Bold | System. Drawing. FontStyle. Italic );
Var brush = new System. Drawing. Drawing2D. LinearGradientBrush (
New Rectangle (0, 0, imageCode. Width, imageCode. Height ),
Color. Blue, Color. DarkRed, 1.2F, true );
G. DrawString (code, font, brush, 2, 2 );

// Foreground noise of the image
For (int I = 0; I <100; I ++)
{
Var x = random. Next (imageCode. Width );
Var y = random. Next (imageCode. Height );
ImageCode. SetPixel (x, y, Color. FromArgb (random. Next ()));
}

// Draw the border line of the image
G. DrawRectangle (new Pen (Color. Silver), 0, 0, imageCode. Width-1, imageCode. Height-1 );
Var MS = new System. IO. MemoryStream ();
ImageCode. Save (MS, System. Drawing. Imaging. ImageFormat. Jpeg );

Response. ClearContent ();
Response. ContentType = "image/Jpeg ";
Response. BinaryWrite (ms. ToArray ());
}
Finally
{
G. Dispose ();
ImageCode. Dispose ();
}

}
# Endregion

Generate a data verification code # region generate a data verification code
Private string GenerateCheckCode ()
{
Int number;
Char code;
String checkCode = String. Empty;

Var random = new Random ();

For (int I = 0; I <5; I ++)
{
Number = random. Next ();

If (number % 2 = 0)
Code = (char) ('0' + (char) (number % 10 ));
Else
Code = (char) ('A' + (char) (number % 26 ));

CheckCode + = code. ToString ();
}
Return checkCode;
}
# Endregion


Verification code page:


Copy codeThe Code is as follows:
<Form id = "formCode" runat = "server">
<Div>

</Div>
</Form>

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.