记录一次图形验证码跟前端交互,给前端图片或者图片转base64两种方法
/**
* 验证码
*/
@ApiOperation("验证码")
@GetMapping("captcha.jpg")
public DataR<Map<String, Object>> captcha(HttpServletResponse response) throws IOException {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
String uuid = UUID.randomUUID().toString().replace("-", "");
// 获取图片验证码
BufferedImage image = sysCaptchaService.getCaptcha(uuid);
// 将图片写入流中,转base64
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", stream);
String base64 = Base64.encode(stream.toByteArray());
stream.flush();
stream.close();
Map<String, Object> result = new HashMap<>();
result.put("image", "data:image/png;base64," + base64);
result.put("uuid", uuid);
return DataR.data(result);
// 发送图片给前端
// ServletOutputStream out = response.getOutputStream();
// ImageIO.write(image, "jpg", out);
// IOUtils.closeQuietly(out);
}
/**
* 使用com.google.code.kaptcha生成验证码图形
*/
public BufferedImage getCaptcha(String uuid) {
// 生成图文验证码
String code = producer.createText();
// 保存验证码和uuid到数据库
SysCaptcha captchaEntity = new SysCaptcha();
captchaEntity.setUuid(uuid);
captchaEntity.setCode(code);
// 5分钟后过期
captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
this.save(captchaEntity);
return producer.createImage(code);
}
最后就是校验图形验证码,结束!