/*
* 1, 字符串类型的验证码
*/
public class VerificationCodeUtil{
/**
* 验证码的来源
*/
final char [] code = {
'0','1','2','3','4','5','6','7','8','9',
'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','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
};
/**
* 字体
*/
final String [] fontNames = {
"黑体","宋体","微软雅黑"
};
/**
* 字体样式
*/
final int [] fontStyles = {
Font.BOLD, Font.ITALIC
};
/**
* 字体大小
*/
private int fontSize = 21;
/**
* 验证码的长度
*/
private int vcodeLen = 4;
/**
* 验证码图片的宽度
*/
private int width = (fontSize+1) * vcodeLen + 10;
/**
*验证码图片的高度
*/
private int height = fontSize+12;
/**
* 干扰线条数
*/
private int disturbline = 4;;
/**
* 生成验证码
* @return 字符串的验证码
*/
public String generatorVCode(){
// 获取字母的字符数组长度
int len = code.length;
Random random = new Random();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < vcodeLen; i++) {
int index = random.nextInt(len);
stringBuffer.append(code[index]);
}
return stringBuffer.toString();
}
/**
* 生成验证码图片
* @param vcode 验证码
* @param drawline 干扰线
* @return 验证码图片
*/
public BufferedImage generatorVCodeImage(String vcode, boolean drawline){
// 创建验证码的图片
BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
graphics.fillRect(0,0,width,height);
graphics.setColor(new Color(198, 189, 108));
if (drawline){
drawDisturbline(graphics);
}
Random random = new Random();
for (int i = 0; i < vcode.length(); i++) {
// 设置字体
graphics.setFont(new Font(fontNames[random.nextInt(fontNames.length)],fontStyles[random.nextInt(fontStyles.length)],fontSize));
// 设置随机颜色
graphics.setColor(getRandomColor());
graphics.drawString(vcode.charAt(i)+"", i * fontSize +10 , fontSize+5);
}
graphics.dispose();
return bufferedImage;
}
/**
* 获取随机颜色
* @return
*/
private Color getRandomColor() {
Random random = new Random();
return new Color( random.nextInt(220),random.nextInt(220),random.nextInt(220));
}
/**
* 生成干扰线
* @param graphics 画笔
* @return 干扰线
*/
private Boolean drawDisturbline(Graphics graphics) {
Random random = new Random();
for (int i = 0; i < disturbline; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
// 设置随机颜色
graphics.setColor(getRandomColor());
// 画画干扰线
graphics.drawLine(x1,y1,x2,y2);
}
return true;
}
}