SpringBoot 图片验证码生成工具、直接上干货
定义CaptchaUtil工具类
package vip.appdesign.suncms.common.utils;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* 验证码生成工具
* @author sun
* @date 2025/7/8
*/
public class CaptchaUtil {
static Random rand = new Random();
/**
* 获取随机字符串
* @param length 获取字符长度
* @return 随机字符串
*/
public static String getRandString(Integer length) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append(chars.charAt(rand.nextInt(chars.length())));
}
return sb.toString();
}
// 生成随机颜色
public static Color getColor() {
return new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
}
/**
* 获取验证码
* @param randomString 随机字符串
* @return BufferedImage
*/
public static BufferedImage getCaptcha(String randomString) {
BufferedImage image = new BufferedImage(160, 60, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
graphics.setColor(Color.BLACK);
//绘制干扰线
for (int i = 0; i < 200; i++) {
int x = rand.nextInt(image.getWidth());
int y = rand.nextInt(image.getHeight());
int x1 = rand.nextInt(x+10);
int y1 = rand.nextInt(y+10);
graphics.setColor(getColor());
graphics.drawLine(x, y, x, y);//参数3和4填写x1,y1可以增加干扰程度
}
graphics.setFont(new Font("Times New Roman", Font.BOLD, 30));
graphics.drawString(randomString + "", 60, 40);
return image;
}
}
对应Controller控制内写法
@RestController
@RequestMapping("/auth")
public class AuthController {
@GetMapping("/captcha")
public void getCapcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
//生成验证码
String captcha = CaptchaUtil.getRandString(4);
//验证码存储到session中
request.getSession().setAttribute("captcha", captcha.toLowerCase());
//生成验证码图片
BufferedImage bufferedImage = CaptchaUtil.getCaptcha(captcha);
//设置响应头
response.setContentType("image/png");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
ImageIO.write(bufferedImage,"png",response.getOutputStream());
}
}
//生成图片截图案例


浙公网安备 33010602011771号