生成验证码的实现方法
public void getValiDateCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
String valiDateCode = request.getParameter("vId");
//生成一张图片
int width = 120;
int height = 48;
//画板
BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
//画笔
Graphics2D gs = buf.createGraphics();
/**
* 绘制矩形,从0,0像素开始
* 设置颜色
*/
gs.setColor(Color.gray);
gs.fillRect(0, 0, width, height);
//干扰线,起点(坐标x,y),终点(坐标x,y),随机取四个数字在图像上连起来,要一百条的话就做个for循环
Random random = new Random();
for (int i = 0; i < 20; i++) {
//设置颜色
gs.setColor(getRandomColor(50, 200));
int x1 = random.nextInt(120);
int y1 = random.nextInt(48);
int x2 = x1+random.nextInt(50);
int y2 = y1+random.nextInt(20);
gs.drawLine(x1, y1, x2, y2);
}
//字体,参数分别是字体设置,样式,加粗,大小
Font font = new Font("宋体", Font.ITALIC, 40);
gs.setFont(font);
//文字颜色
gs.setColor(getRandomColor(1, 100));
//绘制文字
String code = getCode();
gs.drawString(code, 10, 33);
//关闭画笔
gs.dispose();
try {
ImageIO.write(buf, "png", response.getOutputStream());
//将验证码添加到redis中,过期时间300秒
redisClusterService.set(valiDateCode, code,300);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
生成验证码图片方法里面需要引用的方法
/**
* 随机字体颜色
*/
public Color getRandomColor(int from,int to) {
//创建一个随机对象
Random random = new Random();
int r = from+random.nextInt(to-from);
int g = from+random.nextInt(to-from);
int b = from+random.nextInt(to-from);
return new Color(r,g,b);
}
/**
* 拿到随机验证码(大写字母数字组成)
*/
public String getCode() {
Random random = new Random();
char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K','L', 'M', 'N','O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','a','b','c','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z','0','1', '2', '3', '4', '5', '6', '7', '8', '9' };
StringBuffer code = new StringBuffer();
for (int i = 0; i < 4; i++) {
code.append(codeSequence[random.nextInt(codeSequence.length)]);
}
return code.toString();
}
这里生成验证码图片的里面的验证码字母我保存在了redis中,如果你要本地测试的话要将那一行代码去掉,再访问getValiDateCode()方法就可以拿到一张验证码图片了。