Write a verification code generation class containing numbers, Pinyin, and Chinese characters, and a Chinese character Verification Code

Source: Internet
Author: User

Write a verification code generation class containing numbers, Pinyin, and Chinese characters, and a Chinese character Verification Code

We will share with you the following example: Integration 1: lower case pinyin 2: upper case pinyin 3: Number 4: verification code generation class for Chinese characters. It looks very common from the title, yes, it's really common. It's just that when this verification code class is generated, you can specify the rules for the return format of the Verification Code through parameters. What's more, we hope to bring some practicality to everyone, the examples in this Chapter also have a scenario where mvc uses verification code. I hope you will like it.

» Verification code generation Flowchart

» Resolution of the pool code generated by the Verification Code

» Image Verification Code

» Mvc login Operation Test Verification Code correctness

Let's share it one step at a time:

» Verification code generation Flowchart

First, let's take a look at the flowchart of the verification code generation class shared this time:

We can see that the encoding generation pool described in this figure corresponds to several different encoding content. Here, we allow different encoding content to be obtained at the same time based on the parameter settings, so that the verification code can be obtained by combining the text, Pinyin, and Chinese characters, the specific rule settings are determined by parameters;

» Resolution of the pool code generated by the Verification Code

First, we can see from the analysis in the flowchart above that the verification code generation pool needs to obtain data of different types of verification codes in parallel to meet the combined verification code. Therefore, we have the following code:

/// <Summary> /// create a verification code /// </summary> /// <param name = "codeType"> 1: lowercase pinyin 2: uppercase pinyin 3: number 4: Chinese Character </param> // <returns> </returns> public static string CreateCode (string codeType = "1 | 2 | 3 | 4 ") {var code = string. empty; try {if (string. isNullOrWhiteSpace (codeType) | codeType. indexOf ('|') <0) {codeType = "1 | 2 | 3 | 4";} var codeTypeArr = codeType. split (new char [] {'|'}, StringSplitOptions. removeEmptyEntries); var strLen = codeTypeArr. length; // Task <string> [] taskArr = new Task <string> [strLen]; for (int I = 0; I <strLen; I ++) {var val = codeTypeArr [I]; switch (val) {case "1": // lowercase pinyin taskArr [I] = Task. factory. startNew <string> () =>{ return GetPinYinOrUpper (false) ;}); break; case "2": // upper-case pinyin taskArr [I] = Task. factory. startNew <string> () =>{ return GetPinYinOrUpper () ;}); break; case "3": // number taskArr [I] = Task. factory. startNew <string> () =>{ return GetShuZi () ;}); break; case "4": // taskArr [I] = Task. factory. startNew <string> () =>{ return GetHanZi () ;}); break; default: break ;}// wait 30 s until the Task is completed. waitAll (taskArr, TimeSpan. fromSeconds (30); foreach (var item in taskArr) {code + = item. result ;}} catch (Exception ex) {code = "I love my motherland";} return code ;}

The keyword Task is used to distribute tasks to obtain different verification code content. I personally think the most important thing is to set parameters.String codeType = "1 | 2 | 3 | 4"To determine the combination of the Verification Code, which also achieves the diversity of the verification code format;

» Image Verification Code

First of all, we need to make it clear that we want to draw text on an image, so we need to use the Graphics keyword to create a canvas to draw the verification code of our image. Here we first go to the Code:

/// <Summary> /// generate the verification code image stream /// </summary> /// <param name = "code"> Verification code text </param> /// <returns> stream </returns> public static byte [] CreateValidateCodeStream (string code = "I love my motherland ", int fontSize = 18, int width = 0, int height = 0, string fontFamily = "文 ") {var bb = new byte [0]; // initialize the canvas var padding = 2; var len = code. length; width = width <= 0? FontSize * 2 * (len-1) + padding * 4: width; height = height <= 0? FontSize * 2: height; var image = new Bitmap (width, height); var g = Graphics. fromImage (image); try {var random = new Random (); // clear the background color g. clear (Color. white); // draw the horizontal middle interference line var x1 = 0; var y1 = height/2; var x2 = width; var y2 = y1; g. drawLine (new Pen (Color. darkRed), x1, y1, x2, y2); // font var Font = new font (fontFamily, fontSize, (FontStyle. bold | FontStyle. italic); var brush = new LinearGradientBrush (new Rectangle (0, 0, image. width, image. height), Color. blue, Color. darkRed, 1f, true); // draw the text var stringFomart = new StringFormat (); // vertically center stringFomart. lineAlignment = StringAlignment. center; // horizontally centered stringFomart. alignment = StringAlignment. center; var rf = new Rectangle (Point. empty, new Size (width, height); g. drawString (code, font, brush, rf, stringFomart); // foreground disturbance of the picture to be painted for (int I = 0; I <100; I ++) {var x = random. next (image. width); var y = random. next (image. height); image. setPixel (x, y, Color. fromArgb (random. next ();} // draw the border line g of the image. drawRectangle (new Pen (Color. silver), 0, 0, image. width-1, image. height-1); // Save the image stream var stream = new MemoryStream (); image. save (stream, ImageFormat. jpeg); // output image stream bb = stream. toArray ();} catch (Exception ex) {} finally {g. dispose (); image. dispose ();} return bb ;}

This lists the key points of the Verification Code image method:

1. You need to set the height and width of the Image Based on the layout of different pages.

2. interference line: Generally, one or two lines of Verification Code images are used to prevent malicious users from using image recognition software for illegal cracking requests, here, I only set the line code for one day in the horizontal center of the interference line, for example:G. DrawLine (new Pen (Color. DarkRed), x1, y1, x2, y2 );

3. Font: A good-looking font is also a user experience. Therefore, the font can be transmitted as needed;

4. Verify that the Code is in the center of the image. The key code here is:

Var stringFomart = new StringFormat (); // vertically centered stringFomart. LineAlignment = StringAlignment. Center; // horizontally centered stringFomart. Alignment = StringAlignment. Center;

5.G. DrawString (code, font, brush, rf, stringFomart );It is mainly used to draw text on an image. This is the most important part.

6. Generally, the verification code is converted into an image stream, instead of generating an entity Verification Code image and saving it to the server. Otherwise, the server will soon be out of disk space, so

// Save the image stream var stream = new MemoryStream (); image. Save (stream, ImageFormat. Jpeg); // output the image stream bb = stream. ToArray ();

The importance of this sentence can not be ignored, mainly to save the content of the painting to the stream for easy use

7. Never forget to use Dispose to release the canvas.

» Mvc login Operation Test Verification Code correctness

With the verification code generated by the class above, we also need to test and verify the correctness and effect. Below we use the mvc Architecture for testing, first create a verification code test Action and generate the corresponding attempt ValidCode. cshtml file, and then customize several verification codes in different formats to obtain the Action. The Code is as follows:

Public FileResult GetValidateCode () {// return the verification code text var code = string. empty; var bb_code = ValidateCode. getValidateCodeStream (ref code); return File (bb_code, "image/jpeg");} public FileResult GetValidateCode01 () {var code = string. empty; var bb_code = ValidateCode. getValidateCodeStream (ref code, "1 | 2 | 3 | 4"); return File (bb_code, "image/jpeg");} public FileResult GetValidateCode02 () {var code = string. empty; var bb_code = ValidateCode. getValidateCodeStream (ref code, "4 | 3 | 2 | 1"); return File (bb_code, "image/jpeg");} public FileResult GetValidateCode03 () {var code = string. empty; var bb_code = ValidateCode. getValidateCodeStream (ref code, "2 | 2 | 2 | 2"); return File (bb_code, "image/jpeg");} public FileResult GetValidateCode04 () {var code = string. empty; var bb_code = ValidateCode. getValidateCodeStream (ref code, "4 | 4 | 4 | 4"); return File (bb_code, "image/jpeg");} public FileResult GetValidateCode05 () {var code = string. empty; var bb_code = ValidateCode. getValidateCodeStream (ref code, "1 | 1 | 1 | 1"); return File (bb_code, "image/jpeg ");}

It feels almost identical, but the corresponding parameters are different. The following method is followed: the codeType format of the GetValidateCodeStream parameter is: NULL, indicating a free combination of 1: lowercase pinyin 2: uppercase pinyin 3: Number 4: then, enter the following code in the attempt:

<H2> shenniu-Verification Code instance 

Let's take a look at the following:

We can see the differences in the verification code format. This is also the diversity of the verification code format mentioned at the beginning of the article. Of course, there may be other formats that can be ignored temporarily, here is an example of how to click the image to obtain the new verification code and click the login button to go to the background program to determine whether the verification code matches. First, modify the attempt interface code as follows:

@ {ViewBag. title = "ValidtCode ";} 

Then add the following logon verification code to the Controller:

Public JsonResult UserLogin (string code) {var data = new Stage. com. extend. stageModel. moData (); if (string. isNullOrWhiteSpace (code) {data. msg = "Verification code cannot be blank"; return Json (data);} var compareCode = Session ["code"]; if (! CompareCode. equals (code) {data. msg = "Verification code error"; return Json (data);} data. isOk = true; data. msg = "Verification code Verification Successful"; return Json (data);} public FileResult GetValidateCode () {// return the verification code text var code = string. empty; var bb_code = ValidateCode. getValidateCodeStream (ref code); var key = "code"; if (Session [key]! = Null) {Session. Remove (key);} Session [key] = code; return File (bb_code, "image/jpeg ");}

Because I can not capture the dynamic diagram here, click to test to obtain the verification code I here directly give an online example, you can try: http://lovexins.com: 1001/home/ValidCode, the key code for clicking to obtain the new verification code is:$ (This). attr ("src", src );Assign a new value to the scr of the img element. However, you must note that a dynamic parameter must be added when assigning a value to the img element due to browser caching. Here, time is used as the request parameter, therefore, the following code is available:$ (This). attr ("data-src") + "? T = "+ nowTime;This is especially important. Well, let's directly test whether login can judge whether the verification code matches correctly from the backend. Here we use session to save the verification code returned from the image for obtaining the verification code, then, when logging in, determine whether the user data verification code is the same as that of the background session:

Verification Failed:

Verification Successful:

Well, there are so many test cases. If you think that the verification code generation example can be used and you want to use it, please note that the verification code format is different for passing parameters. The main method is:

/// <Summary> /// obtain the verification code image stream /// </summary> /// <param name = "codeLen"> Number of verification codes (codeType Settings> codeLen settings) </param> /// <param name = "codeType"> null indicates a free combination of 1: lowercase pinyin 2: uppercase pinyin 3: Number 4: chinese character </param> /// <returns> </returns> public static byte [] GetValidateCodeStream (ref string code, string codeType = "", int codeLen = 0, int fontSize = 18, int width = 120, int height = 30) {// if (string. isNullOrWhiteSpace (codeType) {for (int I = 0; I <codeLen; I ++) {codeType + = rm. next (1, 5) + "|" ;}} code = CreateCode (codeType); return CreateValidateCodeStream (code, fontSize, width: width, height: height );}

For details about the parameters, refer to the remarks. I will package the code here to facilitate sharing and use: verification code generation example

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.