实现步骤
- 创建画板`
- 创建画笔
- 设置背景
- 设置边框
- 写随机数
- 增加干扰
- 保存备份
- 发送图片
实现代码
public void createCheckCode(HttpServletResponse response,String token) throws IOException {
String baseString ="ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
Random rando= new Random();
char[] randomCharArr = new char[4];
for (int i=0;i<randomCharArr.length;i++){
randomCharArr[i] = baseString.toCharArray()[rando.nextInt(baseString.length())];
}
int width = 120;
int height = 30;
BufferedImage bi= new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
g.setColor(Color.black);
g.drawRect(1, 1, width-2, height-2);
g.setFont(new Font("宋体", Font.ITALIC|Font.BOLD, 30));
g.setColor(Color.red);
for(int i=0;i<randomCharArr.length;i++){
g.drawString(String.valueOf(randomCharArr[i]), i*20+10, 25);
}
g.setColor(Color.black);
int x1,y1,x2,y2;
for(int i=0;i<5;i++){
x1 = rando.nextInt(width);
y1 = rando.nextInt(height);
x2 = rando.nextInt(width);
y2 = rando.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
IObjectCache cache = CacheFactory.getObjectCache();
cache.set("CODE:"+token, new String(randomCharArr));
cache.setExpireTime("CODE:"+token, 5*60);
response.setContentType("image/jpeg");
response.setHeader(TOKEN_NAME, token);
ImageIO.write(bi, "jpg", response.getOutputStream());
}