How to generate a random verification code

1. Create an image object

Create an image object by new a BufferedImage (this is a thread class library package provided in Java), and this image requires three parameters when it is created, namely the width and height of the image and the color of the font

// image
   BufferedImage image =  new BufferedImage(100,40,BufferedImage.TYPE_INT_RGB);

Get graphics through image.getGraphics(). It can be understood as a brush, which can be used to paint step by step.

// 画布
 Graphics graphics = image.getGraphics();

2. Draw random background and text in the image

Next we can draw the background through graphics.

// 设置颜色,默认为黑色
 graphics.setColor(Color.cyan);
// 设置背景填充
  graphics.fillRect(0,0,100,40);

In this way, we draw a rectangular frame with a blue background through the brush. Next, we can draw random text in it. It should be noted here that before we generate random text, we need to change the color currently drawn. Modify font style and size at the same time

   //重新设置画笔的颜色
  graphics.setColor(Color.BLACK);
  // 设置字体样式及大小
  graphics.setFont(new Font("黑体",Font.BOLD,20));

Here simply write a piece of text as a random text.

// 随机文字库
 char[] values = "0123456789abcdefg".toCharArray();

When we have this text library, we only need to randomize the position of an array each time, get a character, and then draw the character into the image

// 利用文字库生成随机的4位验证码
    Random random = new Random();
      for (int i=0;i<4;i++){
    
    
          int index = random.nextInt(values.length);   
          graphics.drawString(String.valueOf(values[index]),10+24*i,30);
      }

3. Turn this image into a local file

Then just use the ImageIO class to write the picture into the specified file.

ImageIO.write(image,"jpg",new File("/Users/zhangyu/Desktop/JavaWeb2/BootAjax/src/main/resources/static/img/abc.jpg"));

The following figure is the random QR code generated this time:
insert image description here

Guess you like

Origin blog.csdn.net/m0_56383107/article/details/127196819