C # draw verification code picture

Posted by Dark_Storm on Sat, 30 Oct 2021 00:21:00 +0200

   with the rise of B/S application system, the security requirements of website login are becoming higher and higher. Generally, verification code will be used to improve the security level of website system.

Verification code business process

  understand the business process of the verification code before realizing the verification code function.

  • 1. When the login interface is opened, the front end will send a network request for verification code data to the back end to obtain the picture data of verification code and the unique mark of verification code picture;
  • 2. The back-end interface randomly generates a verification code text string through request, which is about 6 digits of numbers, letters or Chinese characters;
  • 3. Generate a verification code picture through the generated string, which contains the content of the verification code text string, and add noise, irregular lines, distorted text content, etc. The purpose of this operation is to prevent the machine from attacking by pretending that the real person can recognize the content on the QR code picture while ensuring that the real person can recognize it;
  • 4. After generating the picture, convert the picture into Base64 picture data, generate a unique tag ID, and cache the unique tag ID and verification code text content in the back-end server or database;
  • 5. The back end responds to the Base data and unique tag ID of the verification code picture to the front end, which is used to send the user login information to the back-end login interface for verification when the user logs in;
  • 6. When the user logs in, the back-end interface first verifies whether the verification code is expired and legal. According to the unique tag ID of the verification code picture carried by the user's login request, the cached verification code is obtained and compared with the verification code entered by the user. If the verification code is the same, that is, the verification code is correct. Otherwise, the user will not log in.

Generate verification code

   the task of generating verification code is mainly to generate a Random fixed length string, and try to ensure that the string is Random. Next, I will mainly use Random class to generate a verification code containing numbers and uppercase and lowercase letters.

public static string RandomVerificationCode(int lengths)
{
    string[] chars = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
    string code = "";
    Random random = new Random();
    for (int i = 0; i < lengths; i++)
    {
        code += chars[random.Next(chars.Length)];
    }
    return code;
}

Drawing images in C #

The drawing of images in     C # can be completed mainly by using bitmap and Graphics. Bitmap is used to create a BMP image, and Graphics is used to draw noise, verification code content, etc. on this image. The following code shows the process of drawing verification code in detail.

public static Bitmap DrawImage(string code)
{
    Color[] colors = {
        Color.Red, Color.OrangeRed,Color.SaddleBrown,
        Color.LimeGreen,Color.Green,Color.MediumAquamarine,
        Color.Blue,Color.MediumOrchid,Color.Black,
        Color.DarkBlue,Color.Orange,Color.Brown,
        Color.DarkCyan,Color.Purple
    };
    string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "Song typeface" };
    Random random = new Random();
    // Create a Bitmap image type object
    Bitmap bitmap = new Bitmap(code.Length * 18, 32);
    // Create a graphic brush
    Graphics graphics = Graphics.FromImage(bitmap);
    // Fill the picture background with white
    graphics.Clear(Color.White);
    // Draw verification code noise
    for (int i = 0; i < random.Next(60,80); i++)
    {
        int pointX = random.Next(bitmap.Width);
        int pointY = random.Next(bitmap.Height);
        graphics.DrawLine(new Pen(Color.LightGray,1), pointX, pointY, pointX+1, pointY);
    }
    // Draw 1 random line
    graphics.DrawLine(
            new Pen(colors[random.Next(colors.Length)], random.Next(3)),
            new Point(
                random.Next(bitmap.Width),
                random.Next(bitmap.Height)),
            new Point(random.Next(bitmap.Width),
            random.Next(bitmap.Height)));
    // Draw verification code
    for (int i = 0; i < code.Length; i++)
    {
        graphics.DrawString(
            code.Substring(i, 1),
            new Font(fonts[random.Next(fonts.Length)], 15, FontStyle.Bold),
            new SolidBrush(colors[random.Next(colors.Length)]),
            16 * i + 1,
            random.Next(0, 5)
            );
    }
    // Draw verification code noise
    for (int i = 0; i < random.Next(30, 50); i++)
    {
        int pointX = random.Next(bitmap.Width);
        int pointY = random.Next(bitmap.Height);
        graphics.DrawLine(new Pen(colors[random.Next(colors.Length)], 1), pointX, pointY, pointX, pointY + 1);
    }
    // Draw 1 random line
    graphics.DrawLine(
            new Pen(colors[random.Next(colors.Length)], random.Next(3)),
            new Point(
                random.Next(bitmap.Width),
                random.Next(bitmap.Height)),
            new Point(random.Next(bitmap.Width),
            random.Next(bitmap.Height)));
    return bitmap;
}

   the above method only generates the verification code image into BMP image data. If it is a front-end display, it also needs to convert the image data into Base64 image data. The code is as follows.

public static string BitmapToBase64Str(Bitmap bitmap)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        bitmap.Save(memoryStream, ImageFormat.Jpeg);
        byte[] bytes = memoryStream.ToArray();
        return Convert.ToBase64String(memoryStream.ToArray());
    }
}

summary

    in this case, the difficulty in implementing the verification code mainly lies in the proficiency in the use of Bitmap and Graphics, but in this case, the use is relatively simple and there is no particularly complex content. If you want to realize painting through code, you still need to have a certain ability of graphic imagination. Combined with this case, I made an original code of windows form. As shown at the beginning of the article, my favorite friends can get it and study it.

GitHub: CaptchaImage GitHub
Gitee: CaptchaImage Gitee

Topics: C# Front-end