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

java 简单验证码实现

2018-01-07 00:00 309 查看
编程思路:画板,画笔,添加验证码,添加干扰线,输出验证码图片文件

package cb.verify;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

public class VerifyPhoto {

private static int x1;
private static int x2;
private static int y1;
private static int y2;
private static String str ;
private static String[] color = {"#cccccc","#ff66ff","#660066","#33ffcc","#0033cc","#ff0033","#99ff33","#ffcc66"} ;
private static String[] fond = {"Times New Roman","微软雅黑","新宋体","楷体","黑体"};

//	private static String[] style = {"Font.PLAIN","Font.BOLD","Font.ITALIC","Font.BOLD+Font.ITALIC"};
private static String code = "234567892345678923456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String verifyCode(String path) throws Exception, IOException{
//创建画板
BufferedImage bi = new BufferedImage(100,40, BufferedImage.TYPE_INT_RGB);

//创建画笔
Graphics2D g =  bi.createGraphics();
//设置背景色
g.setBackground(Color.WHITE);
g.fillRect(0, 0, 100, 40);
//		g.fillOval(0, 0, 100, 40);

//画验证码

for(int j=0; j<4; j++){
//随机生成一种字体
g.setFont(new Font(fond[(int)(Math.random()*10/5 -1)], 0, 26));
//随机生成一种颜色
g.setColor(Color.decode(color[(int)(Math.random()*7)]));
System.out.println(g.getColor());
char tmp =code.charAt((int)(Math.random()*72-1));
char[] v1 = {tmp};
int x = (int)(Math.random()*20+j*20);
int y = (int)(Math.random()*20+15);
g.drawChars(v1, 0, 1,x , y);
if(j==0)
str = String.valueOf(tmp);
else
str += String.valueOf(tmp);
}
//画干扰线
g.setColor(Color.BLUE);
for(int i = 0; i<3; i++){
x1 = (int) (Math.random()*30+i*30);
y1 = (int) (Math.random()*40);
x2 = (int) (Math.random()*30+i*20);
y2 = (int) (Math.random()*40);
g.drawLine(x1, y1, x2, y2);
System.out.println("("+x1+","+y1+")"+"("+x2+","+y2+")");
}
for(int i = 0; i<2; i++){
x1 = (int) (Math.random()*20+i*40);
y1 = (int) (Math.random()*40);
x2 = (int) (Math.random()*30+i*40);
y2 = (int) (Math.random()*40);
g.drawLine(x1, y1, x2, y2);
System.out.println("("+x1+","+y1+")"+"("+x2+","+y2+")");
}

//生成图片
ImageIO.write(bi, "png", new FileOutputStream(path));

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