在登录或注册网站时,相信大家都会遇到填写验证码的问题,那么到底为什么要有验证码的存在呢?原因是为了防止个别不法分子利用程序来进行恶意注册,破坏网站的服务器,那么这些验证码是怎么用代码写的呢,现在我就把这些代码贴出来跟大家分享一下
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class VerifyCode {
//确定宽高
private int width = 70;
private int height =40;
private Random random = new Random();
//设置可供选择的字体
private String[] font = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
//设置可供选择的的字符
private String code = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
//设置背景颜色为白色
Color bgColor = new Color(255,255,255);
//设置返回图片字符的String
private String text;
//设置随机颜色
private Color randomColor(){
int red = random.nextInt(150);
int green = random.nextInt(150);
int blue = random.nextInt(150);
return new Color(red,green,blue);
}
//设置字体的随机样式
private Font randomFont(){
int index = random.nextInt(font.length);
int style = random.nextInt(4);
int size = random.nextInt(4)+ 25;
return new Font(font[index],style,size);
}
//设置随机字符
private char randomChar(){
int index = random.nextInt(code.length());
return code.charAt(index);
}
//设置干扰线
private void drawLine(BufferedImage bi){
int num = 3;//画三条线
Graphics2D g = (Graphics2D)bi.getGraphics();
g.setColor(Color.blue);
for (int index = 0;index < num;index++){
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
g.setStroke(new BasicStroke(1.5F));//设置干扰线轮廓
g.drawLine(x1, y1, x2, y2);
}
}
//创建BufferdImage,设置其背景色和边框
private BufferedImage createImage(){
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D)bi.getGraphics();
g.setColor(bgColor);
g.fillRect(0, 0, width, height);
g.setColor(Color.gray);
g.drawRect(0, 0, width - 1, height - 1);
return bi;
}
//调用这个方法得到验证码
public BufferedImage getImage(){
int num = 4;//设置验证码的个数为4个
StringBuffer sb = new StringBuffer();
BufferedImage bi = createImage();
Graphics2D g = (Graphics2D)bi.getGraphics();
for (int index = 0;index < num;index++){
String str = randomChar() + "";
sb.append(str);
float x = index * 1.0F * width / 4;
g.setColor(randomColor());
g.setFont(randomFont());
g.drawString(str, x, height - 5);
}
this.text = sb.toString();
drawLine(bi);
return bi;
}
// 返回验证码图片上的文本
public String getText () {
return text;
}
// 保存图片到指定的输出流
public static void output (BufferedImage image, OutputStream out)
throws IOException {
ImageIO.write(image, "JPEG", out);
}
}