昨天写了一个生成验证码的代码,效果还可以,现在把他贴出来,
//清除缓存。、。。
response.setHeader("Expires", "-1");
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
BufferedImage image=new BufferedImage(Width, Hight,BufferedImage.TYPE_INT_RGB );
Graphics2D graphics=image.createGraphics();
Random random=new Random();
//画出边线
graphics.setColor(Color.blue);
graphics.drawRect(0, 0, 120, 25);
//设置背景
Color bgcolor=colorstyle[random.nextInt(colorstyle.length)];
graphics.setColor(bgcolor);
graphics.fillRect(1, 1, Width, Hight);
for(int i=0;i<4;i++){
//画出干扰线
graphics.setColor(colorstyle[random.nextInt(colorstyle.length)]);
graphics.drawLine(random.nextInt(Width), random.nextInt(Hight),random.nextInt(Width), random.nextInt(Hight));
}
//写出数字(验证码)
int x=5;
String temp="";//存放验证码
for(int i=0;i<4;i++){
char num=Number[random.nextInt(Number.length)];
temp=temp+num;
Color fontcolor=colorstyle[random.nextInt(colorstyle.length)];//字体颜色
while(fontcolor==bgcolor){//不能让字体颜色和背景颜色相同,while循环的好处是当条件满足的时候一直执行while循环,也是和if的本质区别
fontcolor=colorstyle[random.nextInt(colorstyle.length)];
}
graphics.setColor(fontcolor);
graphics.setFont(new Font(fontName[random.nextInt(fontName.length)],fontstyle[random.nextInt(fontstyle.length)], 20));
graphics.drawString(num+"", x, 22);
x+=random.nextInt(20)+10; //控制他们之间的间距,最少是10
}
System.out.println(temp);
HttpSession session=request.getSession();
//将验证码存放进 session
session.setAttribute("yzm", temp);
ImageIO.write(image,"png", response.getOutputStream());
graphics.dispose();
response.flushBuffer();
下面是效果: