java Spring Boot verification code beautification, four random numbers on a white background and a random color for each word

In my previous article, Spring Boot 2.7 generates image verification codes for login and describes the method of generating verification codes.
However, the verification code generated in this way is very ugly.
Insert image description here
Compared with the verification code, it is to be displayed in the web program, so that it is not good for users to see it as true.

We can change the interface to

@GetMapping(value = "/captcha", produces = MediaType.IMAGE_PNG_VALUE)
public void generateCaptcha(HttpServletResponse response) throws IOException {
    
    
    int width = 200;
    int height = 100;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = image.createGraphics();

    // 设置背景为白色
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, width, height);

    // 设置字体和字体大小
    Font font = new Font("Arial", Font.BOLD, 40);
    graphics.setFont(font);

    Random random = new Random();
    // 生成随机颜色并绘制每个字
    for (int i = 0; i < 4; i++) {
    
    
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        Color color = new Color(r, g, b);
        graphics.setColor(color);
        String gin = String.valueOf(random.nextInt(10));
        System.out.println(gin);
        graphics.drawString(gin, 50 * i, 50);
    }

    // 输出图片
    ImageIO.write(image, "png", response.getOutputStream());
    graphics.dispose();
}

Here we generated four random numbers, each with a different color. The bottom of the picture is white.
Gin records the value of each random number. If you want to verify whether the user input is correct, just use them together.

Then we access the interface
Insert image description here
and return a picture like this to us.
Then we see that the console
Insert image description here
gin helps us record the generated values ​​​​in each loop.

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/133067928