public classCheckCodeTool {private Integer width = 80;private Integer height = 38;publicString getCheckCode(BaseForm baseForm) {/** 绘图*/
//step1,创建一个内存映像对象(画板)
BufferedImage image = newBufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//step2,获得画笔
Graphics g =image.getGraphics();//step3,给笔上色//Random r = new Random();
SecureRandom r = newSecureRandom();//g.setColor(new Color(r.nextInt(255), r.nextInt(255),r.nextInt(255)));//step4,给画板设置背景颜色
g.fillRect(0, 0, width, height);//step5,绘制一个随机的字符串
String number =getNumber();
g.setColor(new Color(0, 0, 0));//存储到redis(用于登录校验)
if (baseForm != null &&StringUtils.isNotEmpty(baseForm.getSessionId())) {
String redisCheckCodeId= "CheckCodeId";try{if(RedisUtil.getInstance().isExists(redisCheckCodeId)) {
RedisUtil.getInstance().remove(redisCheckCodeId);
}
RedisUtil.getInstance().setStringWithSeconds(redisCheckCodeId,number,60);//1分钟时效
} catch(Exception e) {
System.out.println("getCheckCode:error:" +e.toString());
}
}//new Font(字体,风格,大小)
g.setFont(new Font(null, Font.ITALIC, 20));
g.drawString(number,5, 25);//step6,加一些干扰线
for (int i = 0; i < 8; i++) {
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}/** 压缩图片并输出到客户端(浏览器)*/ByteArrayOutputStream out= newByteArrayOutputStream();
String base64String= "";try{
ImageIO.write(image,"jpeg", out);
base64String=Base64Utils.encode(out.toByteArray());
}catch(Exception e) {
e.printStackTrace();
}finally{if (out != null) {try{
out.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}returnbase64String;
}//生成随机数作为验证码
privateString getNumber() {
String number= "";
String pool= "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
SecureRandom r= newSecureRandom();for (int i = 0; i < 4; i++) {
number+=pool.charAt(r.nextInt(pool.length()));
}returnnumber;
}
}