SpringBoot生成验证码

这样写代码:

ValidateCodeUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.laisc.wisefire_read.controller;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ValidateCodeUtil {

private static Random random = new Random();
private int width = 165; //验证码的宽
private int height = 45; //验证码的高
private int lineSize = 30; //验证码中夹杂的干扰线数量
private int lineLength = 20; //验证码中夹杂的干扰线长度
private int randomStrNum = 4; //验证码字符个数
private int colorMin = 0; //颜色最低值
private int colorMax = 127; //颜色最高值
private String randomString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWSYZ";
Font font = new Font("Times New Roman", Font.ROMAN_BASELINE, 40);

private Color getRandomColor() {
int r = (int)(Math.random()*(colorMax-colorMin+1)+colorMin);
int g = (int)(Math.random()*(colorMax-colorMin+1)+colorMin);
int b = (int)(Math.random()*(colorMax-colorMin+1)+colorMin);

return new Color(r, g, b);
}

private void drawLine(Graphics g) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(lineLength);
int yl = random.nextInt(lineLength);
g.drawLine(x, y, x + xl, y + yl);

}

public BufferedImage getRandomCodeImage(){

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
g.fillRect(0, 0, width, height);
g.setColor(getRandomColor());
g.setFont(font);
// 干扰线
for (int i = 0; i < lineSize; i++) {
drawLine(g);
}
// 随机字符
String randomStr = "";
for (int i = 0; i < randomStrNum; i++) {
g.setFont(font);
g.setColor(getRandomColor());
String str = String.valueOf(randomString.charAt(random.nextInt(randomString.length())));
g.translate(random.nextInt(3), random.nextInt(6));
g.drawString(str, 40 * i + 10, 25);
}
g.dispose();
return image;
}
}

ValidateCodeController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.laisc.wisefire_read.controller;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

@Controller
@RequestMapping("/validatecode")
public class ValidateCodeController {

@RequestMapping("/showcode")
public void getRandomCodeImage(HttpServletRequest request, HttpServletResponse response){
try {

response.setContentType("image/png");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expire", "0");
response.setHeader("Pragma", "no-cache");
ValidateCodeUtil validateCode = new ValidateCodeUtil();

BufferedImage image = validateCode.getRandomCodeImage();
ImageIO.write(image, "PNG", response.getOutputStream());

} catch (Exception e) {
e.printStackTrace();
}
}

}