天天看點

圖形驗證碼生成工具類

生成驗證碼效果

圖形驗證碼生成工具類
圖形驗證碼生成工具類
圖形驗證碼生成工具類
圖形驗證碼生成工具類

ValidateCode.java 驗證碼生成類

Java代碼  

圖形驗證碼生成工具類
  1. package cn.dsna.util.images;  
  2. import java.awt.Color;  
  3. import java.awt.Font;  
  4. import java.awt.Graphics2D;  
  5. import java.awt.image.BufferedImage;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.OutputStream;  
  9. import java.util.Random;  
  10. import javax.imageio.ImageIO;  
  11. public class ValidateCode {  
  12.     // 圖檔的寬度。  
  13.     private int width = 160;  
  14.     // 圖檔的高度。  
  15.     private int height = 40;  
  16.     // 驗證碼字元個數  
  17.     private int codeCount = 5;  
  18.     // 驗證碼幹擾線數  
  19.     private int lineCount = 150;  
  20.     // 驗證碼  
  21.     private String code = null;  
  22.     // 驗證碼圖檔Buffer  
  23.     private BufferedImage buffImg=null;  
  24.     private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',  
  25.             'K', 'L', 'M', 'N',  'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',  
  26.             'X', 'Y', 'Z',  '1', '2', '3', '4', '5', '6', '7', '8', '9' };  
  27.     public  ValidateCode() {  
  28.         this.createCode();  
  29.     }  
  30.     public  ValidateCode(int width,int height) {  
  31.         this.width=width;  
  32.         this.height=height;  
  33.         this.createCode();  
  34.     }  
  35.     public  ValidateCode(int width,int height,int codeCount,int lineCount) {  
  36.         this.width=width;  
  37.         this.height=height;  
  38.         this.codeCount=codeCount;  
  39.         this.lineCount=lineCount;  
  40.         this.createCode();  
  41.     }  
  42.     public void createCode() {  
  43.         int x = 0,fontHeight=0,codeY=0;  
  44.         int red = 0, green = 0, blue = 0;  
  45.         x = width / (codeCount +2);//每個字元的寬度  
  46.         fontHeight = height - 2;//字型的高度  
  47.         codeY = height - 4;  
  48.         // 圖像buffer  
  49.         buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
  50.         Graphics2D g = buffImg.createGraphics();  
  51.         // 生成随機數  
  52.         Random random = new Random();  
  53.         // 将圖像填充為白色  
  54.         g.setColor(Color.WHITE);  
  55.         g.fillRect(0, 0, width, height);  
  56.         // 建立字型  
  57.         ImgFontByte imgFont=new ImgFontByte();  
  58.         Font font =imgFont.getFont(fontHeight);  
  59.         g.setFont(font);  
  60.         for (int i = 0; i < lineCount; i++) {  
  61.             int xs = random.nextInt(width);  
  62.             int ys = random.nextInt(height);  
  63.             int xe = xs+random.nextInt(width/8);  
  64.             int ye = ys+random.nextInt(height/8);  
  65.             red = random.nextInt(255);  
  66.             green = random.nextInt(255);  
  67.             blue = random.nextInt(255);  
  68.             g.setColor(new Color(red, green, blue));  
  69.             g.drawLine(xs, ys, xe, ye);  
  70.         }  
  71.         // randomCode記錄随機産生的驗證碼  
  72.         StringBuffer randomCode = new StringBuffer();  
  73.         // 随機産生codeCount個字元的驗證碼。  
  74.         for (int i = 0; i < codeCount; i++) {  
  75.             String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);  
  76.             // 産生随機的顔色值,讓輸出的每個字元的顔色值都将不同。  
  77.             red = random.nextInt(255);  
  78.             green = random.nextInt(255);  
  79.             blue = random.nextInt(255);  
  80.             g.setColor(new Color(red, green, blue));  
  81.             g.drawString(strRand, (i + 1) * x, codeY);  
  82.             // 将産生的四個随機數組合在一起。  
  83.             randomCode.append(strRand);  
  84.         }  
  85.         // 将四位數字的驗證碼儲存到Session中。  
  86.         code=randomCode.toString();       
  87.     }  
  88.     public void write(String path) throws IOException {  
  89.         OutputStream sos = new FileOutputStream(path);  
  90.             this.write(sos);  
  91.     }  
  92.     public void write(OutputStream sos) throws IOException {  
  93.             ImageIO.write(buffImg, "png", sos);  
  94.             sos.close();  
  95.     }  
  96.     public BufferedImage getBuffImg() {  
  97.         return buffImg;  
  98.     }  
  99.     public String getCode() {  
  100.         return code;  
  101.     }  
  102. }  

ImgFontByte.java

Java代碼  

圖形驗證碼生成工具類
  1. package cn.dsna.util.images;  
  2. import java.io.ByteArrayInputStream;  
  3. import java.awt.*;  
  4. public class ImgFontByte {  
  5.     public Font getFont(int fontHeight){  
  6.         try {  
  7.             Font baseFont = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(hex2byte(getFontByteStr())));  
  8.             return baseFont.deriveFont(Font.PLAIN, fontHeight);  
  9.         } catch (Exception e) {  
  10.             return new Font("Arial",Font.PLAIN, fontHeight);  
  11.         }  
  12.     }  
  13.     private  byte[] hex2byte(String str) {   
  14.         if (str == null)  
  15.             return null;  
  16.         str = str.trim();  
  17.         int len = str.length();  
  18.         if (len == 0 || len % 2 == 1)  
  19.             return null;  
  20.         byte[] b = new byte[len / 2];  
  21.         try {  
  22.             for (int i = 0; i < str.length(); i += 2) {  
  23.                 b[i / 2] = (byte) Integer  
  24.                         .decode("0x" + str.substring(i, i + 2)).intValue();  
  25.             }  
  26.             return b;  
  27.         } catch (Exception e) {  
  28.             return null;  
  29.         }  
  30.     }   
  31.  private String getFontByteStr(){ return null;  
  32.         return str;//字元串太長 在附件中找  
  33. }  
  34. }  

 ValidateCodeServlet.java Servlet調用方法 

Java代碼  

圖形驗證碼生成工具類
  1. package cn.dsna.util.images;  
  2. import java.io.IOException;  
  3. import javax.servlet.ServletException;  
  4. import javax.servlet.http.HttpServlet;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7. import javax.servlet.http.HttpSession;  
  8. public class ValidateCodeServlet extends HttpServlet {  
  9.     private static final long serialVersionUID = 1L;  
  10.     @Override  
  11.     protected void doGet(HttpServletRequest reqeust,  
  12.             HttpServletResponse response) throws ServletException, IOException {  
  13.         // 設定響應的類型格式為圖檔格式  
  14.         response.setContentType("image/jpeg");  
  15.         //禁止圖像緩存。  
  16.         response.setHeader("Pragma", "no-cache");  
  17.         response.setHeader("Cache-Control", "no-cache");  
  18.         response.setDateHeader("Expires", 0);  
  19.         HttpSession session = reqeust.getSession();  
  20.         ValidateCode vCode = new ValidateCode(120,40,5,100);  
  21.         session.setAttribute("code", vCode.getCode());  
  22.         vCode.write(response.getOutputStream());  
  23.     }  
  24. }  

 測試類

ValidateCodeTest.java

Java代碼  

圖形驗證碼生成工具類
  1. package cn.dsna.util.images;  
  2. import java.io.IOException;  
  3. import java.util.Date;  
  4. public class ValidateCodeTest {  
  5.     public static void main(String[] args) {  
  6.         ValidateCode vCode = new ValidateCode(120,40,5,100);  
  7.         try {  
  8.             String path="D:/t/"+new Date().getTime()+".png";  
  9.             System.out.println(vCode.getCode()+" >"+path);  
  10.             vCode.write(path);  
  11.         } catch (IOException e) {  
  12.             e.printStackTrace();  
  13.         }  
  14.     }  
  15. }  

web.xml 配置

Xml代碼  

圖形驗證碼生成工具類
  1. <servlet>  
  2.     <servlet-name>validateCodeServlet</servlet-name>  
  3.     <servlet-class>cn.dsna.util.images.ValidateCodeServlet</servlet-class>  
  4. </servlet>      
  5. <servlet-mapping>  
  6.     <servlet-name>validateCodeServlet</servlet-name>  
  7.     <url-pattern>*.images</url-pattern>  
  8. </servlet-mapping>  

繼續閱讀