|
图形验证码是一个Servlet,该Servlet在运行中动态地生成不同的图片。这种动态生成图片不仅可以用于图形验证码,还可以生成各种统计图表,样例图等。
若生成统计图表则需要连接数据库,获取数据记录。此处的图形验证码则相对较为简单,系统获取随机数字,最为ASCII码,得出相对应的字母值,然后将这些字母显示在图片中,另外再为图片额外生成一些随机线条。
public class AuthImg extends HttpServlet {
// 设置
private static String CONTENT_TYPE = "text/html;charset=gb2312";
// 设置生成图形验证码里字母的字体、大小
private Font mFont = new Font("Tims New Roman", Font.PLAIN, 17);
public void init() throws ServletException {
super.init();
}
// 用于获取随机颜色
Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int red = fc + random.nextInt(bc - fc);
int green = fc + random.nextInt(bc - fc);
int blue = fc + random.nextInt(bc - fc);
return new Color(red, green, blue);
}
// Servlet的响应方法
public void servie(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应的文件头
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 表明生成的响应是图片,而非JSP页面
response.setContentType("image/jpeg");
// 设置图片大小
int width = 100, height = 18;
// 在内存中生成图片
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 开始制作图像
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(1, 1, width - 1, height - 1);
g.setColor(new Color(102, 102, 102));
g.drawRect(0, 0, width - 1, height - 1);
g.setFont(mFont);
g.setColor(getRandColor(160, 200));
// 画随机线条
for (int j = 0; j < 150; j++) {
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int x1 = random.nextInt(6) + 1;
int y1 = random.nextInt(12) + 1;
g.drawLine(x, y, x + x1, y + y1);
}
// 从另外一个方向画随机线条
for (int j = 0; j < 70; j++) {
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int x1 = random.nextInt(12) + 1;
int y1 = random.nextInt(6) + 1;
g.drawLine(x, y, x - x1, y - y1);
}
// 生成随机数,并将随机数字转换成字母
String sRand = "";
for (int j = 0; j < 6; j++) {
// 生成65到91的随机数字
int itmp = random.nextInt(26) + 65;
char ctmp = (char) itmp;
sRand += String.valueOf(ctmp);
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
// 将字母依次输出到图片中
g.drawString(String.valueOf(ctmp), 15 * j + 10, 16);
}
// 将随机产生的字符串房在session中
HttpSession session = request.getSession(true);
session.setAttribute("rand", sRand);
g.dispose();
// 将图片输出到Servlet响应
ImageIO.write(image, "JPEG", response.getOutputStream());
}
public void destroy() {
}
} |
|