SoFunction
Updated on 2025-04-04

Implementing graphic verification code tool class based on Java

Tools:

package ;

import .slf4j.Slf4j;

import ;
import .*;
import ;
import ;
import ;
import ;

/**
  * Verification code tool class
  *
  * @author wangbo
  * @since 2024/10/29
  */
@Slf4j
public class CaptchaGeneratorUtil {

    private CaptchaGeneratorUtil() {
        // ...
    }

    public static void main(String[] args) throws IOException {
        // Generate 4-bit random digital verification code        String text = generateRandomCode();
        // Create verification code picture        BufferedImage image = createImage(text);
        // Save the picture to the file        (image, "png", new File(""));
    }

    private static final SecureRandom RANDOM = new SecureRandom();

    /**
      * Generate 4-digit random number letter verification code
      */
    public static String generateRandomCode() {
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int i1 = (3);
            if (i1 == 0) {
                ((char) ((26) + 65));
            } else if (i1 == 1) {
                ((char) ((26) + 97));
            } else {
                ((10));
            }
        }
        ("The generated verification code text text = {}", code);
        return ();
    }

    /**
      * Create verification code picture
      */
    public static BufferedImage createImage(String text) {
        ("Text of the verification code image to be generated text = {}", text);
        int width = 75;
        int height = 25;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // Use Graphics2D for better graphics control        Graphics2D g2d = ();

        try {
            // Set background color            (new Color(0xDCDCDC));
            (0, 0, width, height);

            // Set font and color            (new Font("Arial", , 20));
            (new Color(0x004000));

            // Make sure the text does not exceed the image boundary            FontMetrics fm = ();
            int textWidth = (text);
            // Chinese text            int x = (width - textWidth) / 2;
            // Centered text (baseline alignment)            int y = (height - ()) / 2 + ();

            (text, x, y);

            // Add noise lines            for (int i = 0; i < 5; i++) {
                (new Color((255), (255), (255)));
                ((width), (height), (width), (height));
            }

            // Set rendering prompts to improve image quality (optional)            (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        } finally {
            // Make sure to release Graphics2D resources after the try block            ();
        }

        return image;
    }

    private static final String CAPTCHA_PREFIX = "captcha:";

    public static String generateCaptchaRedisKey(String key) {
        return CAPTCHA_PREFIX + key;
    }
}

Generate image verification code interface (this interface does not require permission verification):

/**
  * Generate image verification code
  *
  * @param key UUID string
  */
@GetMapping("/captcha/generator/{key}")
public void captchaGenerator(@PathVariable("key") String key, HttpServletResponse response) throws BaseException {
    (key, response);
}
public void captchaGenerator(String key, HttpServletResponse response) throws BaseException {
    // Check whether the key's verification code already exists    String captchaRedisKey = (key);
    boolean hasKey = ((captchaRedisKey));
    if (hasKey) {
        throw new BaseException(ErrorCode.USER_KEY_REPETITION);
    }
    String captcha = ();
    BufferedImage image = (captcha);
    //Set the verification code, valid for 1 minute    ().set(captchaRedisKey, captcha, 60L, );
    ("image/jpeg");
    try (ServletOutputStream out = ()) {
        (image, "JPEG", out);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Log in to the interface or other interfaces involving verification codes to verify the verification code:

//Calculation verification codeString key = ();
String captcha = ();
if ((key) || (captcha)) {
    throw new BaseException(ErrorCode.USER_KEY_OR_CAPTCHA_NOT_FOUND);
}
String captchaRedisKey = (key);
String redisCaptcha = ().get(captchaRedisKey);
if ((redisCaptcha) || !(redisCaptcha)) {
    throw new BaseException(ErrorCode.USER_CAPTCHA_ERROR);
} else {
    //Delete the verification code cache    (captchaRedisKey);
}

This is the end of this article about implementing graphic verification code tools based on Java. For more related Java graphics verification code content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!