Implement a verification code generation class (with numbers, pinyin, kanji)

Source: Internet
Author: User
Tags browser cache
Since I ca n’t intercept the dynamic image here, I clicked the test to get the verification code. I will give an example online here. You can try it: http://lovexins.com:1001/home/ValidCode. Click to get the key The code is: $ (this) .attr ("src", src); Re-assign the scr of the img element, but note that due to the browser cache, you need to add a dynamic parameter when assigning the value. Here I am The time is used as the request parameter, so the following code is available: $ (this) .attr ("src") "? T =" nowTime; This is a special place to pay attention to; OK, let's directly test whether the login can be accessed from The backend judges whether the verification code matches correctly. Here, the session is used to save the verification code returned by obtaining the verification code picture, and then it is determined whether the verification code of the user data is the same as the verification of the background session when logging in:

verification failed:

Verification succeeded:

Well, there are so many test cases. If you think that this verification code generation example is okay and you want to use it, please note that the parameters are passed in different formats, and the main method is:



This article and everyone to share is an integration 1: lowercase pinyin; 2: uppercase pinyin; 3: number; 4: The Code generation class for Chinese characters. The example in this chapter will also have a scenario where MVC uses CAPTCHA validation. Have a certain reference value, follow the small series below to see it




This time and everyone to share is an integration 1: lowercase pinyin 2: uppercase Pinyin 3: Number 4: Chinese character verification code generation class, from the title to feel very common, yes, it is very common, but this code class generation can be specified by the parameter code to return the format of the rules, The main thing is to hope to bring a certain degree of practicality, this chapter will also have an example of MVC use verification code to verify the scene, I hope you can like.



» Verification Code Generation flowchart



» Validation code Generation Pool Code parsing



» Draw the verification code onto the image



» MVC Login Operation test Verification code correctness



The following step by step to share:



» Verification Code Generation flowchart



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






Can see this figure describes the code generation pool corresponding to a number of different encoding content, which is mainly based on the parameter settings allow the simultaneous acquisition of different encoding content, to reach the text, pinyin, Chinese characters combined into a verification code, the specific rules set by the parameters;



» Validation code Generation Pool Code parsing



First, from the above analysis of the content of the flowchart can be seen, this verification code generation pool need to obtain different types of verification code data in parallel to meet the combined verification code, so the following code:





/// <summary>
 /// create verification code
 /// </ summary>
 /// <param name = "codeType"> 1: lower case pinyin 2: upper case 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
 Task <string> [] taskArr = new Task <string> [strLen];
 for (int i = 0; i <strLen; i ++)
 {
  var val = codeTypeArr [i];
  switch (val)
  {
  case "1": // lower case pinyin
  taskArr [i] = Task.Factory.StartNew <string> (() => {return GetPinYinOrUpper (false);});
  break;
  case "2": // Capitalization
  taskArr [i] = Task.Factory.StartNew <string> (() => {return GetPinYinOrUpper ();});
  break;
  case "3": // number
  taskArr [i] = Task.Factory.StartNew <string> (() => {return GetShuZi ();});
  break;
  case "4": // Chinese character
  taskArr [i] = Task.Factory.StartNew <string> (() => {return GetHanZi ();});
  break;
  default:
  break;
  }
 }
 // wait for completion 30s
 Task.WaitAll (taskArr, TimeSpan.FromSeconds (30));
 foreach (var item in taskArr)
 {
  code + = item.Result;
 }
 }
 catch (Exception ex)
 {
 code = "I love the motherland";
 }
 return code;
 }


Here continue to use the keyword task, to distribute the task to obtain different verification code content, personally think the most important or through the parameter set string codetype = "1|2|3|4" , to determine the combination of verification code, which also achieves the multiplicity of verification code format;



» Draw the verification code onto the image



First of all, I want to make it clear that the text is drawn on a certain image, then need to use the Graphics keyword, so as to create a canvas to draw our verification code to the picture, here first on the code:





/// <summary>
 /// Generate a verification code image stream
 /// </ summary>
 /// <param name = "code"> Verification code text </ param>
 /// <returns> stream </ returns>
 public static byte [] CreateValidateCodeStream (string code = "I love the motherland", int fontSize = 18, int width = 0, int height = 0, string fontFamily = "Chinese font"
 {
 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 background color
 g.Clear (Color.White);
 // Draw 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 text
 var stringFomart = new StringFormat ();
 // center vertically
 stringFomart.LineAlignment = StringAlignment.Center;
 // center horizontally
 stringFomart.Alignment = StringAlignment.Center;
 var rf = new Rectangle (Point.Empty, new Size (width, height));
 g.DrawString (code, font, brush, rf, stringFomart);
 // Draw the foreground interference point of the picture
 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 of the picture
 g.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 is a key point to list the method of drawing Captcha Image:



1. The height and width of the picture need to be set, this depends on the layout of different pages, so here it is high and wide as parameter passing



2. Interference line: Usually the verification code pictures are one or two lines of interference, mainly to prevent some malicious users using the image recognition software for irregular crack requests, I here the interference line only set the horizontal center of the day straight line code such as: g.drawline (New Pen ( color.darkred), x1, y1, x2, y2);



3. Font: A nice looking font is usually also a user experience, so here the font is passed according to the required parameters;



4. Verify that the code is centered horizontally in the picture, where the key code is:





var stringFomart = new StringFormat ();
  // center vertically
  stringFomart.LineAlignment = StringAlignment.Center;
  // center horizontally
  stringFomart.Alignment = StringAlignment.Center;


5. g.drawstring (code, font, brush, RF, stringfomart); Mainly used to draw the text to the picture, this is the most important place



6. What do we usually do? Verify the code into the picture stream, instead of actually generating an entity with the captcha image saved to the server, otherwise the server will soon be running out of disk, so





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


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



7. Finally don't forget to use Dispose to release the canvas



» MVC Login Operation test Verification code correctness



With the above code generation class generated a good code picture, then we also need to test the correctness and effectiveness of the validation, the following we use the MVC architecture to do the test, Create a verification code to test the action and generate the corresponding attempt to validcode.cshtml the file, and then customize several different formats of the verification code to get the action, the code is as follows:





public FileResult GetValidateCode ()
 {
 // Returned 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");
 }


Feel almost exactly the same, but the corresponding parameters are not the same, the method followed here Getvalidatecodestream parameter CodeType format is: null for the free combination of 1: lowercase pinyin 2: uppercase Pinyin 3: Number 4: Chinese characters; then we're going to fill in the following code:


<h2> Shenniu-Verification Code Example </ h2>
<p class = "container" id = "appVue">
 <table class = "table table-bordered text-left">
 <tbody>
 <tr>
 <td> All random </ td>
 <td>
  <img src = "/ home / GetValidateCode" src = "/ home / GetValidateCode" id = "imgCode" />
  <input type = "text" name = "code" placeholder = "Please enter a verification code" class = "form-control" />
  <button class = "btn btn-default"> Sign in </ button>
  <span id = "msg" style = "color: red"> </ span>
 </ td>
 </ tr>
 <tr>
 <td> lowercase | uppercase | numbers | Chinese characters </ td>
 <td> <img src = "/ home / GetValidateCode01" src = "/ home / GetValidateCode01" /> </ td>
 </ tr>
 <tr>
 <td> Chinese character | number | uppercase | lowercase </ td>
 <td> <img src = "/ home / GetValidateCode02" src = "/ home / GetValidateCode02" /> </ td>
 </ tr>
 <tr>
 <td> Capitalize all </ td>
 <td> <img src = "/ home / GetValidateCode03" src = "/ home / GetValidateCode03" /> </ td>
 </ tr>
 <tr>
 <td> All Chinese characters </ td>
 <td> <img src = "/ home / GetValidateCode04" src = "/ home / GetValidateCode04" /> </ td>
 </ tr>
 <tr>
 <td> All lowercase </ td>
 <td> <img src = "/ home / GetValidateCode05" src = "/ home / GetValidateCode05" /> </ td>
 </ tr>
 </ tbody>
 </ table>
</ p>






Well, let's generate the project, look as follows:

You can see the difference between our 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 composition formats. Please allow me to ignore them. Let ’s make a click on the picture to get a new verification code Function and click the login button to go to the background program to determine whether the verification code matches the example, first modify the attempt interface code as follows:


@ {
 ViewBag.Title = "ValidtCode";
}
<h2> Shenniu-Verification Code Example </ h2>
<p class = "container" id = "appVue">
 <table class = "table table-bordered text-left">
 <tbody>
 <tr>
 <td> All random </ td>
 <td>
  <img src = "/ home / GetValidateCode" src = "/ home / GetValidateCode" id = "imgCode" />
  <input type = "text" name = "code" placeholder = "Please enter a verification code" class = "form-control" />
  <button class = "btn btn-default"> Sign in </ button>
  <span id = "msg" style = "color: red"> </ span>
 </ td>
 </ tr>
 <tr>
 <td> lowercase | uppercase | numbers | Chinese characters </ td>
 <td> <img src = "/ home / GetValidateCode01" src = "/ home / GetValidateCode01" /> </ td>
 </ tr>
 <tr>
 <td> Chinese character | number | uppercase | lowercase </ td>
 <td> <img src = "/ home / GetValidateCode02" src = "/ home / GetValidateCode02" /> </ td>
 </ tr>
 <tr>
 <td> Capitalize all </ td>
 <td> <img src = "/ home / GetValidateCode03" src = "/ home / GetValidateCode03" /> </ td>
 </ tr>
 <tr>
 <td> All Chinese characters </ td>
 <td> <img src = "/ home / GetValidateCode04" src = "/ home / GetValidateCode04" /> </ td>
 </ tr>
 <tr>
 <td> All lowercase </ td>
 <td> <img src = "/ home / GetValidateCode05" src = "/ home / GetValidateCode05" /> </ td>
 </ tr>
 </ tbody>
 </ table>
</ p>
<script src = "~ / Scripts / jquery-1.10.2.min.js"> </ script>
<script type = "text / javascript">
 $ (function () {
 $ ("img"). on ("click", function () {
 var nowTime = new Date (). getTime ();
 var src = $ (this) .attr ("src") + "? t =" + nowTime;
 if (src.length <= 0) {return;}
 $ (this) .attr ("src", src);
 });
 $ ("button"). on ("click", function () {
 var msg = $ ("# msg");
 var code = $ ("input [name = 'code']"). val ();
 if (code.length <= 0) {msg.html ("Please enter the verification code!"); return;}

 $ .post ("/ home / UserLogin", {code: code}, function (result) {
 if (result) {
  msg.html (result.Msg);
  if (! result.IsOk) {
  $ ("# imgCode"). click ();
  }
 }
 });
 })
 })
</ script>







Then add the following login verification code to the Controller:


public JsonResult UserLogin (string code)
  {
  var data = new Stage.Com.Extend.StageModel.MoData ();
  if (string.IsNullOrWhiteSpace (code)) {data.Msg = "The verification code cannot be empty"; return Json (data);}
  var compareCode = Session ["code"];
  if (! compareCode.Equals (code)) {data.Msg = "Authentication code error"; return Json (data);}
  data.IsOk = true;
  data.Msg = "Verification code verification succeeded";
  return Json (data);
  }
  public FileResult GetValidateCode ()
  {
  // Returned 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");
  }








Since I ca n’t intercept the dynamic image here, I clicked the test to get the verification code. I will give an example online here. You can try it: http://lovexins.com:1001/home/ValidCode. Click to get the key The code is: $ (this) .attr ("src", src); Re-assign the scr of the img element, but note that due to the browser cache, you need to add a dynamic parameter when assigning the value. Here I am The time is used as the request parameter, so the following code is available: $ (this) .attr ("src") "? T =" nowTime; This is a special place to pay attention to; OK, let's directly test whether the login can be accessed from The backend judges whether the verification code matches correctly. Here, the session is used to save the verification code returned by obtaining the verification code picture, and then it is determined whether the verification code of the user data is the same as the verification of the background session when logging in:

verification failed:

Verification succeeded:

Well, there are so many test cases. If you think that this verification code generation example is okay and you want to use it, please note that the parameters are passed in different formats, and the main method is:




/// <summary>
  /// get verification code image stream
  /// </ summary>
  /// <param name = "codeLen"> Number of verification codes (codeType setting> codeLen setting) </ param>
  /// <param name = "codeType"> null means free combination 1: lower case pinyin 2: upper case 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)
  {
  // is empty free combination
  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 the specific parameters, please see the comments. I'll package the code here for easy sharing and use: a verification code generation example


 
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.