SoFunction
Updated on 2025-03-07

Method for generating verification code pictures in C#

The examples in this article share with you the specific code of C# generation verification code image for your reference. The specific content is as follows

/// <summary>
    /// Generate verification code picture    /// </summary>
    /// <returns></returns>
    public byte[] GetVerifyCode()
    {
      int codeW = 80;
      int codeH = 40;
      int fontSize = 18;
      string chkCode = ;
      //Color list, used for verification code, noise lines, noise points      Color[] color = { , , , , , , ,  };
      //Font list, used for verification code      string[] font = { "Times New Roman" };
      //The character set of verification code has been removed, some easily confusing characters have been removed      char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
      Random rnd = new Random();
      //Generate verification code string      for (int i = 0; i < 4; i++)
      {
        chkCode += character[()];
      }

      //Create a canvas      Bitmap bmp = new Bitmap(codeW, codeH);
      Graphics g = (bmp);
      ();
      //Draw noise lines      for (int i = 0; i < 1; i++)
      {
        int x1 = (codeW);
        int y1 = (codeH);
        int x2 = (codeW);
        int y2 = (codeH);
        Color clr = color[()];
        (new Pen(clr), x1, y1, x2, y2);
      }
      //Draw the verification code string      for (int i = 0; i < ; i++)
      {
        string fnt = font[()];
        Font ft = new Font(fnt, fontSize);
        Color clr = color[()];
        (chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
      }
      //Write the verification code image to the memory stream and output it in "image/Png" format      MemoryStream ms = new MemoryStream();
      try
      {
        (ms, );
        return ();
      }
      catch (Exception)
      {
        return null;
      }
      finally
      {
        ();
        ();
      }
    }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.