Understand the process of generating verification code by C

  • 2021-09-11 21:06:43
  • OfStack

This paper introduces the detailed process of generating verification code for everyone's reference, and the specific contents are as follows

The class that generates the verification code:


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;

namespace Controllers.Core.Util
{
  /// <summary>
  ///  Verification code 
  /// </summary>
  public class VerifyCodeHelper : AdminBaseController
  {
    #region  Variable 
    /// <summary>
    ///  Color table 
    /// </summary>
    private static Color[] colors = new Color[]{
      Color.FromArgb(220,20,60),
      Color.FromArgb(128,0,128),
      Color.FromArgb(65,105,225),
      Color.FromArgb(70,130,180),
      Color.FromArgb(46,139,87),
      Color.FromArgb(184,134,11),
      Color.FromArgb(255,140,0),
      Color.FromArgb(139,69,19),
      Color.FromArgb(0,191,255),
      Color.FromArgb(95,158,160),
      Color.FromArgb(255,20,147),
      Color.FromArgb(255,165,0)};

    /// <summary>
    ///  Font list 
    /// </summary>
    private static string[] fonts = new string[] { 
      "Arial",
      "Verdana", 
      "Georgia", 
      " Blackbody " };

    /// <summary>
    ///  Font size 
    /// </summary>
    private static int fontSize = 22;
    #endregion

    #region  Generate verification code picture 
    /// <summary>
    ///  Generate verification code picture 
    /// </summary>
    public static Bitmap CreateVerifyCodeBmp(out string code)
    {
      int width = 120;
      int height = 40;
      Bitmap bmp = new Bitmap(width, height);
      Graphics g = Graphics.FromImage(bmp);
      Random rnd = new Random();

      // Background color 
      g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, width, height));

      // Text 
      StringBuilder sbCode = new StringBuilder();
      for (int i = 0; i < 4; i++)
      {
        string str = GetChar(rnd);
        Font font = GetFont(rnd);
        Color color = GetColor(rnd);
        g.DrawString(str, font, new SolidBrush(color), new PointF((float)(i * width / 4.0), 0));
        sbCode.Append(str);
      }
      code = sbCode.ToString();

      // Noise line 
      for (int i = 0; i < 10; i++)
      {
        int x1 = rnd.Next(bmp.Width);
        int x2 = rnd.Next(bmp.Width);
        int y1 = rnd.Next(bmp.Height);
        int y2 = rnd.Next(bmp.Height);

        Pen p = new Pen(GetColor(rnd), 1);
        g.DrawLine(p, x1, y1, x2, y2);
      }

      // Twist 
      bmp = TwistImage(bmp, true, 3, rnd.NextDouble() * Math.PI * 2);
      g = Graphics.FromImage(bmp);

      // Noise 
      for (int i = 0; i < 100; i++)
      {
        int x1 = rnd.Next(bmp.Width);
        int y1 = rnd.Next(bmp.Height);

        Pen p = new Pen(GetColor(rnd), 1);
        g.DrawRectangle(p, x1, y1, 1, 1);
      }

      // Border 
      g.DrawRectangle(new Pen(new SolidBrush(Color.FromArgb(153, 153, 153))), new Rectangle(0, 0, width - 1, height - 1));

      return bmp;
    }
    #endregion

    #region  Get random characters 
    /// <summary>
    ///  Get random characters 
    /// </summary>
    private static string GetChar(Random rnd)
    {
      int n = rnd.Next(0, 61);
      if (n <= 9)
      {
        return ((char)(48 + n)).ToString();
      }
      else if (n <= 35)
      {
        return ((char)(65 + n - 10)).ToString();
      }
      else
      {
        return ((char)(97 + n - 36)).ToString();
      }
    }
    #endregion

    #region  Get random fonts 
    /// <summary>
    ///  Get random fonts 
    /// </summary>
    private static Font GetFont(Random rnd)
    {
      return new Font(fonts[rnd.Next(0, fonts.Length)], fontSize, FontStyle.Bold);
    }
    #endregion

    #region  Get random colors 
    /// <summary>
    ///  Get random colors 
    /// </summary>
    private static Color GetColor(Random rnd)
    {
      return colors[rnd.Next(0, colors.Length)];
    }
    #endregion

    #region  Sinusoidal curve Wave Distorted picture 
    /// <summary>  
    ///  Sinusoidal curve Wave Distorted picture ( Edit By 51aspx.com )   
    /// </summary>  
    /// <param name="srcBmp"> Picture path </param>  
    /// <param name="bXDir"> If it is distorted, select True</param>  
    /// <param name="nMultValue"> The larger the amplitude multiple of the waveform, the higher the degree of distortion, 1 Be general 3</param>  
    /// <param name="dPhase"> Initial phase and value interval of waveform [0-2*PI)</param>  
    private static System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
    {
      System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

      //  Fill the bitmap background with white   
      System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
      graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
      graph.Dispose();

      double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

      for (int i = 0; i < destBmp.Width; i++)
      {
        for (int j = 0; j < destBmp.Height; j++)
        {
          double dx = 0;
          dx = bXDir ? (Math.PI * 2 * (double)j) / dBaseAxisLen : (Math.PI * 2 * (double)i) / dBaseAxisLen;
          dx += dPhase;
          double dy = Math.Sin(dx);

          //  Gets the color of the current point   
          int nOldX = 0, nOldY = 0;
          nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
          nOldY = bXDir ? j : j + (int)(dy * dMultValue);

          System.Drawing.Color color = srcBmp.GetPixel(i, j);
          if (nOldX >= 0 && nOldX < destBmp.Width
           && nOldY >= 0 && nOldY < destBmp.Height)
          {
            destBmp.SetPixel(nOldX, nOldY, color);
          }
        }
      }

      return destBmp;
    }
    #endregion

  }
}

Verification code page Action:


public ActionResult VerifyCode()
{
  string code;
  Bitmap bmp = VerifyCodeHelper.CreateVerifyCodeBmp(out code);
  Bitmap newbmp = new Bitmap(bmp, 108, 36);
  HttpContext.Session["VerifyCode"] = code;

  Response.Clear();
  Response.ContentType = "image/bmp";
  newbmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Bmp);

  return View();
}

The foreground page is empty cshtml page, verification code in the value of Session.

Pages that use verification codes:

img that displays the verification code:

< img id= "verifyCode" src= "" alt= "Verification Code" style= "vertical-align: middle; "/ >
After the page is loaded, the verification code is displayed (note that the time stamp should be added, otherwise the verification code will not be refreshed when the page is refreshed):


$(function () {
  // Refresh verification code 
  $("#refreshVerifyCode").click(function () {
    refreshVerifyCode(); // Refresh verification code 
  });
  $("#verifyCode").click(function () {
    refreshVerifyCode(); // Refresh verification code 
  });
  refreshVerifyCode();
});

Refresh verification code:


// Refresh verification code 
function refreshVerifyCode() {
  $("#verifyCode").attr("src", "VerifyCode?t=" + new Date().valueOf());
}
 

Action for judging whether the text entered by the user is the same as the verification code:


public ActionResult CheckVCode(string vcode)
{
  if (HttpContext.Session["VerifyCode"].ToString().ToLower() == vcode.ToLower())
  {
    Dictionary<string, object> dic = new Dictionary<string, object>();
    dic["ok"] = true;
    return Content(JsonConvert.SerializeObject(dic));
  }
  else
  {
    Dictionary<string, object> dic = new Dictionary<string, object>();
    dic["ok"] = false;
    return Content(JsonConvert.SerializeObject(dic));
  }
}

The above is the whole content of this article, hoping to help everyone learn the method of generating verification code by C #.


Related articles: