首先创建一个类的成员变量:
// w,h为图片的宽高
private int w= 70;
private int h= 35;
//创建一个Random类的对象
private Random r = new Random();
//字体数组
private String[] fontName = {"宋体","华文楷体","黑体","微软雅黑","楷体_GB_2312"};
//可选字符
private String codes = "23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//背景色
private Color bgColor = new Color(255, 255, 255);
//验证码字符串
private String text;
随机获取字体的颜色:
private Color randomColor() {
//选取150以下的避免看不清
int red = r.nextInt(150);
int green = r.nextInt(150);
int bule = r.nextInt(150);
return new Color(red,green,bule);
}
随机获取字体Font:
private Font randomFont() {
int index = r.nextInt(fontName.length);
String fontname = fontName[index];
//获取随机的样式,0(无样式),1(粗体),2(斜体),3(粗体斜体);
int style = r.nextInt(4);
//生成随机字号大小 范围在24 - 28,避免字体太小
int size = r.nextInt(5) + 24;
return new Font(fontname, style, size);
}
画三条验证码的干扰线
private void drawLine (BufferedImage image) {
//画三条
int num = 3 ;
//获取画笔
Graphics2D g2 = (Graphics2D) image.getGraphics();
for(int i = 0; i<num;i++) {
//生成两个点的坐标,即4个值
int x1 = r.nextInt(w);
int y1 = r.nextInt(h);
int x2 = r.nextInt(w);
int y2 = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));
//设置干扰线的颜色是蓝色
g2.setColor(Color.BLUE);
g2.drawLine(x1, y1, x2, y2);
}
}
随机获取字符:
private char randomChar() {
//随机获取codes的索引
int index = r.nextInt(codes.length());
return codes.charAt(index);
}
画图:
private BufferedImage createImage() {
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 =(Graphics2D) image.getGraphics();
g2.setColor(this.bgColor);
g2.fillRect(0, 0, w,h);
return image;
}
获取验证码:
public BufferedImage getImage() {
//创建图片缓冲区
BufferedImage image = createImage();
//得到绘制环境
Graphics2D g2 = (Graphics2D) image.getGraphics();
//用来装载生成的文本
StringBuilder sb = new StringBuilder();
//循环4次每次生成一个字符
for(int i =0;i<4;i++) {
//随机生成一个字母
String s = randomChar()+"";
sb.append(s);
//设置当前字符的x轴坐标
float x = i * 1.0F * w/4;
g2.setFont(randomFont());
g2.setColor(randomColor());
g2.drawString(s, x, h-5);
}
this.text = sb.toString();
//添加干扰线
drawLine(image);
return image;
}
获取生成验证码的文本:
public String getText() {
return text;
}
保存图片到指定输出流:
public static void output(BufferedImage image,OutputStream outputstream) throws IOException {
ImageIO.write(image,"JPEG", outputstream);
}
创建好之后直接调用这个类就可以生成随机的验证码;
public static void main(String[] args) throws FileNotFoundException, IOException {
Yanzhengma yzm = new Yanzhengma();
BufferedImage image = yzm.getImage();
Yanzhengma.output(image, new FileOutputStream("D:\\xxx.jpg"));
String text =yzm.getText();
Scanner sc = new Scanner(System.in);
System.out.println("请输入验证码:");
String test = sc.nextLine();
if(text.equals(test)) {
System.out.println("恭喜验证成功");
}else {
System.out.println("验证失败,请重新输入");
}
}