@GetMapping(value = "/randomImage")
public SysResult randomImage(HttpServletResponse response){
SysResult sysResult = new SysResult();
try {
//生成验证码
final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";
String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
//存到redis中
// String lowerCaseCode = code.toLowerCase();
//
// String realKey = Md5Util.md5Encode(lowerCaseCode+key, "utf-8");
// log.info("获取验证码,Redis checkCode = {},key = {}", code, key);
// redisUtil.set(realKey, lowerCaseCode, 60);
//返回前端
String base64 = RandImageUtil.generate(code);
log.info("验证码为:"+code);
sysResult.setData(base64);
} catch (Exception e) {
sysResult.setMsg("获取验证码出错"+e.getMessage());
e.printStackTrace();
}
return sysResult;
}
验证码工具类
直接生成图片返回给前端
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;
public class RandImageUtil {
public static final String key = "JEECG_LOGIN_KEY";
private static final int width = 105;
private static final int height = 35;
private static final int count = 200;
private static final int lineWidth = 2;
private static final String IMG_FORMAT = "JPEG";
private static final String BASE64_PRE = "data:image/jpg;base64,";
public static void generate(HttpServletResponse response, String resultCode) throws IOException {
BufferedImage image = getImageBuffer(resultCode);
// 输出图象到页面
ImageIO.write(image, IMG_FORMAT, response.getOutputStream());
}
public static String generate(String resultCode) throws IOException {
BufferedImage image = getImageBuffer(resultCode);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
//写入流中
ImageIO.write(image, IMG_FORMAT, byteStream);
//转换成字节
byte[] bytes = byteStream.toByteArray();
//转换成base64串
String base64 = Base64.getEncoder().encodeToString(bytes).trim();
//删除 rn
base64 = base64.replaceAll("n", "").replaceAll("r", "");
//写到指定位置
//ImageIO.write(bufferedImage, "png", new File(""));
return BASE64_PRE+base64;
}
private static BufferedImage getImageBuffer(String resultCode){
// 在内存中创建图象
final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
final Graphics2D graphics = (Graphics2D) image.getGraphics();
// 设定背景颜色
// ---1
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
// 设定边框颜色
// graphics.setColor(getRandColor(100, 200)); // ---2
graphics.drawRect(0, 0, width - 1, height - 1);
final Random random = new Random();
// 随机产生干扰线,使图象中的认证码不易被其它程序探测到
for (int i = 0; i < count; i++) {
// ---3
graphics.setColor(getRandColor(150, 200));
// 保证画在边框之内
final int x = random.nextInt(width - lineWidth - 1) + 1;
final int y = random.nextInt(height - lineWidth - 1) + 1;
final int xl = random.nextInt(lineWidth);
final int yl = random.nextInt(lineWidth);
graphics.drawLine(x, y, x + xl, y + yl);
}
// 取随机产生的认证码
for (int i = 0; i < resultCode.length(); i++) {
// 将认证码显示到图象中,调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
// graphics.setColor(new Color(20 + random.nextInt(130), 20 + random
// .nextInt(130), 20 + random.nextInt(130)));
// 设置字体颜色
graphics.setColor(Color.BLACK);
// 设置字体样式
// graphics.setFont(new Font("Arial Black", Font.ITALIC, 18));
graphics.setFont(new Font("Times New Roman", Font.BOLD, 24));
// 设置字符,字符间距,上边距
graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26);
}
// 图象生效
graphics.dispose();
return image;
}
private static Color getRandColor(int fc, int bc) { // 取得给定范围随机颜色
final Random random = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
final int r = fc + random.nextInt(bc - fc);
final int g = fc + random.nextInt(bc - fc);
final int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
前端代码:
将得到的数据结果放入即可
结果:
校验验证码:
//获得用户发过来的验证码 进行校验
String captcha = sysLoginModel.getCaptcha();//获得验证码
if(captcha==null){
result.error500("验证码无效");
return result;
}
//去除大小写
String lowerCaseCaptcha = captcha.toLowerCase();
//与redis中的进行比对。----------------
String realKey = Md5Util.md5Encode(lowerCaseCaptcha+sysLoginModel.getCheckKey(), "utf-8");
Object checkCode = redisUtil.get(realKey);
//当进入登录页时,有一定几率出现验证码错误 #1714
if(checkCode==null || !checkCode.toString().equals(lowerCaseCaptcha)) {
log.warn("验证码错误,key= {} , Ui checkCode= {}, Redis checkCode = {}", sysLoginModel.getCheckKey(), lowerCaseCaptcha, checkCode);
result.error500("验证码错误");
return result;
}



