import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public class CodeKey{
//这里设置字符串的编码。
private static final char [] code = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890".toCharArray();
//captcha为验证码
private String captcha = null;
//验证码图片的高度宽度
private int height;
private int width;
//验证码的长度
private int codeKey_Len;
//背景颜色
private Color backgroundColor;
public String getCaptcha() {
return captcha;
}
//width验证码图片宽度、height验证码图片高度、backgroundColor验证码图片背景颜色、codeKey_Len验证码的长度
public CodeKey(int width, int height, Color backgroundColor, int codeKey_Len){
this.height = height;
this.width = width;
this.codeKey_Len = codeKey_Len;
this.backgroundColor = backgroundColor;
MakeCaptcha();
}
//生成随机的验证码
private String MakeCaptcha(){
this.captcha = "";
for(int i = 0;i<codeKey_Len;i++) {
Random random = new Random();
//随机获取字符
this.captcha += CodeKey.code[random.nextInt(CodeKey.code.length)];
}
return this.captcha;
}
//生成验证码图片
public BufferedImage getCodeKeyImage(){
//如果没有在获取captcha之前就生成图片,就会自动生成一次。
System.out.println(this.captcha);
BufferedImage codeKeyImage = new BufferedImage(this.width,this.height,BufferedImage.TYPE_INT_RGB);
Random random = new Random();
Graphics grp = codeKeyImage.getGraphics();
//绘制背景颜色
grp.setColor(this.backgroundColor);
grp.fillRect(0,0,this.width,this.height);
for(int i = 0;i<codeKey_Len;i++){
//对应字符的位置和颜色进行随机
int keysize = random.nextInt(this.width/this.codeKey_Len/3)+3*this.width/this.codeKey_Len/4;
int keyTop = this.height/3+random.nextInt(this.height-this.height/3);
int keyLeft = i*this.width/this.codeKey_Len + random.nextInt(this.width/this.codeKey_Len/2);
grp.setColor(new Color(random.nextInt(150), random.nextInt(200), random.nextInt(200)));
grp.setFont(new Font(Font.SANS_SERIF,Font.PLAIN,keysize));
grp.drawString(this.captcha.charAt(i)+"",keyLeft,keyTop);
}
//随机画线
for(int i=0;i<random.nextInt(8)+3;i++){
grp.setColor(new Color(random.nextInt(150), random.nextInt(200), random.nextInt(200)));
grp.drawLine(0,random.nextInt(this.height),this.width,random.nextInt(this.height));
}
return codeKeyImage;
}
}
使用:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
CodeKey codeKey = new CodeKey(120,60, Color.white,4);
// 将生成的验证码code放入sessoin中
req.getSession().setAttribute("captcha",codeKey.getCaptcha());
ImageIO.write(codeKey.getCodeKeyImage(),"JPG",resp.getOutputStream());
}
效果如下: