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));
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)];
for(int i=0;i<4;i++){
if(i==0){
setValidateCode("");
}
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;
}
}