- 创建图形验证码实体类
@Slf4j
public class Captcha {
public BufferedImage Captcha(){
//创建一张图片
int width = 120;
int height = 20;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//创建一支画笔
Graphics2D graphics2D = image.createGraphics();
//填充颜色
graphics2D.setColor(Color.white);
graphics2D.fillRect(0,0,width,height);
String str = this.getString();
Random random = new Random();
// 根据验证码长度随机画干扰线(颜色随机,位置随机,长度随机)
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
Font font = new Font("微软雅黑", Font.BOLD, 22);
graphics2D.setFont(font);
Color color = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
graphics2D.setColor(color);
graphics2D.drawString(String.valueOf(c), 20 + i * 15, 20);
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
graphics2D.drawLine(x1, y1, x2, y2);
}
// 把图像刷到BufferedImage对象中
graphics2D.dispose();
return image;
}
public String getString(){
Random random = new Random();
String str = "";
for(int i = 0;i < 4;i++){
int num = random.nextInt(3);
switch (num){
case 0:
int number = random.nextInt(10);
str +=number;
break;
case 1:
int lower = random.nextInt(26) + 97;
str += (char)lower;
break;
case 2:
int upper = random.nextInt(26) + 67;
str += (char)upper;
break;
default:
System.out.println("error");
break;
}
}
log.info("str:" + str);
return str;
}
}
2.实现Controller接口
@RestController
public class CaptchaController {
@RequestMapping("/image")
public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
Captcha captcha = new Captcha();
BufferedImage image = captcha.Captcha();
ImageIO.write(image,"JPEG",response.getOutputStream());
}
}
3.实现前段页面
<body>
<a href="javascript:getVerifiCode()">
<img id="yzm_img" style="cursor:pointer;width: 100px;height: 36px;margin: 5px 0 0 5px;border-radius: 3px;" title="点击刷新验证码" src="/image"/>
</a>
</body>