dome
/**
* @ClassName : VerifyCodeController
* @Description : 图片验证码
* @Author : llh
* @Date: 2024-03-22 10:48
*/
@Controller
@RequestMapping("/verifycode")
public class VerifyCodeController {
@Resource
private StringRedisTemplate stringRedisTemplate;
@GetMapping
public void verifyCode(String username , HttpServletResponse response ) throws IOException {
//字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
//宽
int IMG_WIDTH = 72;
//高
int IMG_HEIGTH = 27;
Random random = new Random();
//创建图片
BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGTH, BufferedImage.TYPE_INT_RGB);
//画板
Graphics g = image.getGraphics();
//填充背景
g.setColor(Color.WHITE);
//填充边框
g.fillRect(1,1,IMG_WIDTH-2,IMG_HEIGTH-2);
//设置字体
g.setFont(new Font("楷体", Font.BOLD,25));
StringBuilder stringCode = new StringBuilder();
//写字
for(int i = 1 ; i <= 4 ; i ++){
//随机颜色
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
//随机位置
int len = random.nextInt(VERIFY_CODES.length());
//随机字母
String str = VERIFY_CODES.substring(len,len+1);
//追加
stringCode.append(str);
//写入
g.drawString(str, IMG_WIDTH / 6 * i , 22 );
}
//将验证码存放到redis数据库中
stringRedisTemplate.opsForValue().set( "login" + username , stringCode.toString() , 1 , TimeUnit.HOURS);
// 干扰线
for (int i = 0; i < 30; i++) {
//随机颜色
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
//随机位置
int x = random.nextInt(IMG_WIDTH - 1);
int y = random.nextInt(IMG_HEIGTH - 1);
int x1 = random.nextInt(12) + 1;
int y1 = random.nextInt(6) + 1;
g.drawLine(x, y, x - x1, y - y1);
}
//响应到浏览器
ImageIO.write(image,"jpeg", response.getOutputStream());
}
}
redus数据
接口数据