您的位置:首页 > 编程语言 > Java开发

写一个自己的验证码工具类

2016-05-14 23:23 369 查看
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
*@author frunqer
*@time 2016年5月13日 下午9:31:47
*@note 这是生成验证码的帮助类
*/
public class ValidateCode {
private static String validateCode=""; //定义静态变量用来存放生成的验证码
/**
* @author frunqer
* @time 2016年5月13日 下午9:28:00
* @tags @param width 矩形验证码宽
* @tags @param height 验证码高
* @tags @param size  验证码字体大小
* @tags 这是获得验证码图片的方法
*/
public static BufferedImage getImage(int width,int height,int size){
//创建一个缓冲图片
BufferedImage image=new BufferedImage(90, 40, BufferedImage.TYPE_INT_BGR);
//创建一个随机数
Random random=new Random();
//创建一个画笔
Graphics g=image.getGraphics();
//画一个矩形
g.fillRect(0, 0, width, height);
//定义一个可选字符范围
char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
int length=ch.length;
//定义一个随机颜色
Color color=new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
//定义5中随机字体
Font[] fonts=new Font[5];
fonts[0]=new Font("Ravie", Font.PLAIN, size);
fonts[1]=new Font("Autique olive compact", Font.PLAIN, size);
fonts[2]=new Font("Forte",Font.PLAIN,size);
fonts[3]=new Font("Wide Latin", Font.PLAIN,size);
fonts[4]=new Font("Gill Sans Ultra Bold", Font.PLAIN, size);
Font font=fonts[random.nextInt(5)];
//生成4位字符验证码
for(int i=0;i<4;i++){
if(i==0){
setValidateCode(""); //每次重新生成验证码前 要将validateCode值清空
}
g.setFont(font);//设置字体样式
String code=new Character(ch[random.nextInt(length)]).toString();//设置单个随机字符
ValidateCode.setValidateCode(getValidateCode() + code);
g.setColor(color);
g.drawString(code, 20*i+6, 25);
}
//生成干扰线
for(int i=0;i<100;i++){
int x=random.nextInt(width);
int y=random.nextInt(height);
g.drawOval(x, y, 2, 2);

}
g.dispose();
return image;

}

//这是获得验证码内容的方法
public static String getValidateCode() {
return validateCode;
}
public static void setValidateCode(String validateCode) {
ValidateCode.validateCode = validateCode;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  验证码 java