图形码 图形验证码

2006/5/31

验证码产生类:

package com.gicom.testCode;

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 java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * 生成随机数字或字母串,以图像方式显示,用于人工识别,使程序很难识别。减小系统被程序自动攻击的可能性。
 * 生成的图形颜色由红、黑、蓝、紫4中随机组合而成,数字或字母垂直方向位置在一定范围内也是随机的,减少被程序自动识别的几率。
 * 由于数字的0,1,2易和字母的o,l,z混淆,使人眼难以识别,因此不生成数字和字母的混合串。生成的串字母统一用小写,串的最大长度为16。
 *
 * @version
 * @Since
 * @See Also
 * @author lchen Create Date 2005-12-16
 *
 */

public class CreateValidImage {
 // 字符的高度和宽度,单位为像素
 private int wordHeight = 9;

 private int wordWidth = 12;

 // 字符大小
 private int fontSize = 13;

 // 最大字符串个数
 private static final int MAX_CHARCOUNT = 16;

 // 垂直方向起始位置
 private final int initypos = 5;

 // 要生成的字符个数,由工厂方法得到
 private int charCount = 0;

 // 随机生成字体样式
 private static int[] font = { Font.BOLD, Font.ITALIC, Font.PLAIN };

 // 随机生成字符串时选择的数组

 private static String[] arr = { "2", "3", "4", "5", "6", "7", "8", "9",
   "A", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P",
   "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

 // 随机数生成器
 private Random r = new Random();

 /**
  * 生成图像的格式常量,JPEG格式,生成为文件时扩展名为.jpg;输出到页面时需要设置MIME type 为image/jpeg
  */
 public static String GRAPHIC_JPEG = "JPEG";

 /**
  * 生成图像的格式常量,PNG格式,生成为文件时扩展名为.png;输出到页面时需要设置MIME type 为image/png
  */
 public static String GRAPHIC_PNG = "PNG";

 // 用工厂方法创建对象
 protected CreateValidImage(int charCount) {
  this.charCount = charCount;
 }

 /**
  * 创建对象的工厂方法
  *
  * @param charCount
            要生成的字符个数,个数在1到16之间
  *
  * Return 返回RandomGraphic对象实例
  * @throws Exception
             参数charCount错误时抛出
  */
 public static CreateValidImage createInstance(int charCount)
   throws Exception {
  if (charCount < 1 || charCount > MAX_CHARCOUNT) {
   throw new Exception(
     "Invalid parameter charCount,charCount should between in 1 and 16");
  }
  return new CreateValidImage(charCount);
 }

 /**
  * 随机生成一个字母和数字混合的串,并以图像方式绘制,绘制结果输出到流out中
  *
  * @param graphicFormat
            设置生成的图像格式,值为GRAPHIC_JPEG或GRAPHIC_PNG
  * @param out
            图像结果输出流
  * @return 随机生成的串的值
  * @throws IOException
  */
 public String drawAlpha(String graphicFormat, OutputStream out)
   throws IOException {
  // 随机生成的串的值
  String charValue = "";
  charValue = randAlphaAndNumber();
  return draw(charValue, graphicFormat, out);

 }

 /**
  * 以图像方式绘制字符串,绘制结果输出到流out中
  *
  * @param charValue
            要绘制的字符串
  * @param graphicFormat
            设置生成的图像格式,值为GRAPHIC_JPEG或GRAPHIC_PNG
  * @param out
            图像结果输出流
  * @return 随机生成的串的值
  * @throws IOException
  */
 protected String draw(String charValue, String graphicFormat,
   OutputStream out) throws IOException {

  // 计算图像的宽度和高度
  int w = (charCount + 2) * wordWidth;
  int h = wordHeight * 3;

  // 创建内存图像区
  BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
  Graphics2D g = bi.createGraphics();

  // 设置背景色
  g.setColor(getRandColor(200, 250));
  g.fillRect(0, 0, w, h);
  // 绘制边框
  g.setColor(Color.black);
  g.drawRect(0, 0, w - 1, h - 1);
  // 生成干扰线
  g.setColor(getRandColor(160, 200));
  for (int i = 0; i < 155; i++) {
   // g.setColor(getRandColor(160, 200));
   int x = r.nextInt(w);
   int y = r.nextInt(h);
   int xl = r.nextInt(12);
   int yl = r.nextInt(12);
   g.drawLine(x, y, x + xl, y + yl);
  }
  g.setColor(getRandColor(100, 159));
  for (int i = 0; i < 80; i++) {
   int x = r.nextInt(w);
   int y = r.nextInt(h);
   g.drawLine(x, y, x, y);
  }

  // 设置font
  // 绘制charValue,每个字符颜色随机
  for (int i = 0; i < charCount; i++) {
   g.setFont(new Font(null, font[randomInt(0, font.length)],
     randomInt(15, 19)));
   // g.setFont(new Font(null,Font.BOLD,randomInt(15,19)));
   String c = charValue.substring(i, i + 1);
   g.setColor(new Color(20 + r.nextInt(20), 20 + r.nextInt(20), 20 + r
     .nextInt(20)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
   int xpos = (i + 1) * wordWidth;
   // 垂直方向上随机
   int ypos = randomInt(initypos + wordHeight, initypos + wordHeight
     * 2);
   g.drawString(c, xpos, ypos);
  }
  g.dispose();
  bi.flush();
  // 输出到流
  ImageIO.write(bi, graphicFormat, out);

  return charValue;
 }

 // 生成随机数字和字符组合的字符串
 private String randAlphaAndNumber() {
  String charValue = "";
  for (int i = 0; i < charCount; i++) {
   String c = arr[randomInt(0, arr.length)];
   charValue += c;
  }
  return charValue;
 }

 /**
  * 返回[from,to)之间的一个随机整数
  *
  * @param from
            起始值
  * @param to
            结束值
  * @return [from,to)之间的一个随机整数
  */
 protected int randomInt(int from, int to) {
  // Random r = new Random();
  return from + r.nextInt(to - from);
 }

 private static Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
  Random random = new Random();
  if (fc > 255)
   fc = 255;
  if (bc > 255)
   bc = 255;
  int r = fc + random.nextInt(bc - fc);
  int g = fc + random.nextInt(bc - fc);
  int b = fc + random.nextInt(bc - fc);
  return new Color(r, g, b);
 }

 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {

  for (int i = 0; i < 10; i++) {
   System.out.println(CreateValidImage.createInstance(6).drawAlpha(
     CreateValidImage.GRAPHIC_JPEG,
     new FileOutputStream("e:/jpg/myimg" + i + ".jpg")));
  }
 }
}

在Servlet中调用:

package com.gicom.testCode;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GraphicServlet extends HttpServlet {

 public GraphicServlet() {
  super();

 }

 protected void doGet(HttpServletRequest req, HttpServletResponse res)
   throws IOException, ServletException {

  // 设置输出内容为图像,格式为jpeg
  res.setContentType("image/jpg");
  try {
   // 将内容输出到响应客户端对象的输出流中,生成的图片中包含6个字符

   String v = CreateValidImage.createInstance(6).drawAlpha(
     CreateValidImage.GRAPHIC_JPEG, res.getOutputStream());
   // 将字符串的值保留在session中,便于和用户手工输入的验证码比较,比较部分不是本文讨论重点,故略

   req.getSession().setAttribute("rv", v);
  } catch (Exception e) {

   e.printStackTrace();
  }
 }
}

在JSP页面中产生图片:

<%@page contentType="text/html;charset=gb2312" language="java"%>
<%response.setHeader("Pragma", "No-cache");
   response.setHeader("Cache-Control", "no-cache");
   response.setHeader("Expires", "Thu, 01 Dec 1900 16:00:00 GMT");
   response.setDateHeader("Expires", -1);
   %>
<html>
 <head>
  <title>图形代码页面</title>
 </head>
 <body>
  <form action="" method="post" name="form1">
   <input type="text" name="validateCode" />
   验证码:
   <img src='<%=request.getContextPath()%>/RandImage'/>
   <br>
   <input type="submit" value="提交" οnclick="a()">
  </form>
 </body>
</html>


原理:

产生图形码的同时,把产生的字符串存放在Session对象中,在其他的类中和用户提交过来的字符串进行比对。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值