Java后端实现随机验证码图片生成
/**
* 生成随机验证码图片
*/
@RestController
public class CaptchaController {
/**
* 生成随机验证码
*/
@RequestMapping("/captcha")
public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 设置响应头信息
response.setContentType("image/png");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 验证码图片的宽度和高度
int width = 100;
int height = 36;
// 创建 BufferedImage 对象,设置图片大小和类型
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取 Graphics2D 对象,绘制图片
Graphics2D g = image.createGraphics();
// 生成随机数,作为验证码
String captcha = generateRandomString();
request.getSession().setAttribute("captcha", captcha);
// 设置字体、字号和颜色
Font font = new Font("Arial", Font.PLAIN, 20);
g.setFont(font);
g.setColor(Color.BLACK);
// 绘制验证码
g.drawString(captcha, 20, 25);
// 添加干扰线和噪点
addInterference(g, width, height);
// 输出图片
ImageIO.write(image, "png", response.getOutputStream());
}
/**
* 生成随机字符串
*/
private String generateRandomString() {
String base = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 添加干扰线和噪点
*/
private void addInterference(Graphics2D g, int width, int height) {
Random random = new Random();
// 添加干扰线
for (int i = 0; i < 3; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.drawLine(x1, y1, x2, y2);
}
// 添加噪点
for (int i = 0; i < 30; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.fillRect(x, y, 1, 1);
}
}
}
下载地址
用户评论