一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Java生成图形验证码工具类

时间:2017-03-24 编辑:简简单单 来源:一聚教程网

生成验证码效果

ValidateCode.java 验证码生成类

 代码如下 复制代码

packagecn.dsna.util.images;

importjava.awt.Color;

importjava.awt.Font;

importjava.awt.Graphics2D;

importjava.awt.image.BufferedImage;

importjava.io.FileOutputStream;

importjava.io.IOException;

importjava.io.OutputStream;

importjava.util.Random;

importjavax.imageio.ImageIO;

/**

 * 验证码生成器

 * @author dsna

 *

 */

publicclassValidateCode {

 // 图片的宽度。

 privateintwidth =160;

 // 图片的高度。

 privateintheight =40;

 // 验证码字符个数

 privateintcodeCount =5;

 // 验证码干扰线数

 privateintlineCount =150;

 // 验证码

 privateString code =null;

 // 验证码图片Buffer

 privateBufferedImage buffImg=null;

 privatechar[] codeSequence = {'A','B','C','D','E','F','G','H','I','J',

   'K','L','M','N','P','Q','R','S','T','U','V','W',

   'X','Y','Z','1','2','3','4','5','6','7','8','9'};

 publicValidateCode() {

  this.createCode();

 }

 /**

  *

  * @param width 图片宽

  * @param height 图片高

  */

 publicValidateCode(intwidth,intheight) {

  this.width=width;

  this.height=height;

  this.createCode();

 }

 /**

  *

  * @param width 图片宽

  * @param height 图片高

  * @param codeCount 字符个数

  * @param lineCount 干扰线条数

  */

 publicValidateCode(intwidth,intheight,intcodeCount,intlineCount) {

  this.width=width;

  this.height=height;

  this.codeCount=codeCount;

  this.lineCount=lineCount;

  this.createCode();

 }

 publicvoidcreateCode() {

  intx =0,fontHeight=0,codeY=0;

  intred =0, green =0, blue =0;

  x = width / (codeCount +2);//每个字符的宽度

  fontHeight = height -2;//字体的高度

  codeY = height -4;

  // 图像buffer

  buffImg =newBufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

  Graphics2D g = buffImg.createGraphics();

  // 生成随机数

  Random random =newRandom();

  // 将图像填充为白色

  g.setColor(Color.WHITE);

  g.fillRect(0,0, width, height);

  // 创建字体

  ImgFontByte imgFont=newImgFontByte();

  Font font =imgFont.getFont(fontHeight);

  g.setFont(font);

  for(inti =0; i < lineCount; i++) {

   intxs = random.nextInt(width);

   intys = random.nextInt(height);

   intxe = xs+random.nextInt(width/8);

   intye = ys+random.nextInt(height/8);

   red = random.nextInt(255);

   green = random.nextInt(255);

   blue = random.nextInt(255);

   g.setColor(newColor(red, green, blue));

   g.drawLine(xs, ys, xe, ye);

  }

  // randomCode记录随机产生的验证码

  StringBuffer randomCode =newStringBuffer();

  // 随机产生codeCount个字符的验证码。

  for(inti =0; i < codeCount; i++) {

   String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);

   // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。

   red = random.nextInt(255);

   green = random.nextInt(255);

   blue = random.nextInt(255);

   g.setColor(newColor(red, green, blue));

   g.drawString(strRand, (i +1) * x, codeY);

   // 将产生的四个随机数组合在一起。

   randomCode.append(strRand);

  }

  // 将四位数字的验证码保存到Session中。

  code=randomCode.toString(); 

 }

 publicvoidwrite(String path)throwsIOException {

  OutputStream sos =newFileOutputStream(path);

   this.write(sos);

 }

 publicvoidwrite(OutputStream sos)throwsIOException {

   ImageIO.write(buffImg,"png", sos);

   sos.close();

 }

 publicBufferedImage getBuffImg() {

  returnbuffImg;

 }

 publicString getCode() {

  returncode;

 }

}

ImgFontByte.java

 代码如下 复制代码

packagecn.dsna.util.images;

importjava.io.ByteArrayInputStream;

importjava.awt.*;

/**

 * ttf字体文件

 * @author dsna

 *

 */

publicclassImgFontByte {

 publicFont getFont(intfontHeight){

  try{

   Font baseFont = Font.createFont(Font.TRUETYPE_FONT,newByteArrayInputStream(hex2byte(getFontByteStr())));

   returnbaseFont.deriveFont(Font.PLAIN, fontHeight);

  }catch(Exception e) {

   returnnewFont("Arial",Font.PLAIN, fontHeight);

  }

 }

 privatebyte[] hex2byte(String str) {

  if(str ==null)

   returnnull;

  str = str.trim();

  intlen = str.length();

  if(len ==0|| len %2==1)

   returnnull;

  byte[] b =newbyte[len /2];

  try{

   for(inti =0; i < str.length(); i +=2) {

    b[i /2] = (byte) Integer

      .decode("0x"+ str.substring(i, i +2)).intValue();

   }

   returnb;

  }catch(Exception e) {

   returnnull;

  }

 }/**

 * ttf字体文件的十六进制字符串

 * @return

 */

 privateString getFontByteStr(){returnnull;

  returnstr;//字符串太长 在附件中找

}

}

ValidateCodeServlet.java Servlet调用方法

 代码如下 复制代码

packagecn.dsna.util.images;

importjava.io.IOException;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

publicclassValidateCodeServletextendsHttpServlet {

 privatestaticfinallongserialVersionUID = 1L;

 @Override

 protectedvoiddoGet(HttpServletRequest reqeust,

   HttpServletResponse response)throwsServletException, IOException {

  // 设置响应的类型格式为图片格式

  response.setContentType("image/jpeg");

  //禁止图像缓存。

  response.setHeader("Pragma","no-cache");

  response.setHeader("Cache-Control","no-cache");

  response.setDateHeader("Expires",0);

  HttpSession session = reqeust.getSession();

  ValidateCode vCode =newValidateCode(120,40,5,100);

  session.setAttribute("code", vCode.getCode());

  vCode.write(response.getOutputStream());

 }

/**

 * web.xml 添加servlet

 

  validateCodeServlet

  cn.dsna.util.images.ValidateCodeServlet

  

 

  validateCodeServlet

  *.images

 

在地址栏输入XXX/dsna.images 测试

 */

}

 测试类

 代码如下 复制代码

ValidateCodeTest.java

packagecn.dsna.util.images;

importjava.io.IOException;

importjava.util.Date;

publicclassValidateCodeTest {

 /**

  * @param args

  */

 publicstaticvoidmain(String[] args) {

  ValidateCode vCode =newValidateCode(120,40,5,100);

  try{

   String path="D:/t/"+newDate().getTime()+".png";

   System.out.println(vCode.getCode()+" >"+path);

   vCode.write(path);

  }catch(IOException e) {

   e.printStackTrace();

  }

 }

}

web.xml 配置

 代码如下 复制代码

 validateCodeServlet

 cn.dsna.util.images.ValidateCodeServlet

 

 validateCodeServlet

 *.images

热门栏目