廢話不多說,直接上代碼!
/**
* @Description: 擷取驗證碼圖檔
* @params
* @Author: czw
* @return
* @CreateDate: 2021/3/1 10:32
*/
@RequestMapping("/get_verify_code")
@ResponseBody
public void getVerifyCode(String uuid, HttpServletResponse response) throws IOException {
int width = 120; // 驗證碼圖檔寬度
int height = 40; // 驗證碼圖檔長度
int length = 4; // 驗證碼位數
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(VerifyCodeUtil.getRandColor(185, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.ITALIC, 35));
g.setColor(VerifyCodeUtil.getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
StringBuilder sRand = new StringBuilder();
for (int i = 0; i < length; i++) {
String rand = String.valueOf(VerifyCodeUtil.getRandomString(random.nextInt(VerifyCodeUtil.randString.length())));
sRand.append(rand);
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 25 * i + 12, 32);
}
//7.将随機驗證碼存入redis緩存并設定過期時間,設定過期時間20分鐘
stringRedisTemplate.opsForValue().set(uuid,sRand.toString(),60 * 20,TimeUnit.SECONDS);
//8.設定響應頭通知浏覽器以圖檔的形式打開
response.setContentType("image/jpeg");//等同于response.setHeader("Content-Type", "image/jpeg");
//9.設定響應頭控制浏覽器不要緩存
response.setDateHeader("expries", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
//10.将圖檔寫給浏覽器
ImageIO.write(image, "jpg", response.getOutputStream());
}
上工具類
/**
* @author czw
* @version 1.0
* @date 2021/3/1 9:31
* @remark 生成驗證碼工具類
*/
public class VerifyCodeUtil {
public static String randString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//随機字元串
/**
* 擷取随機的字元
*/
public static String getRandomString(int num) {
return String.valueOf(randString.charAt(num));
}
/**
* 擷取顔色
*/
public static Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
效果圖如下
