网站推荐、资源下载等 | 个人网站

【转】java图形验证码生成工具类

生成验证码效果

 

 

 

 

  1 package cn.dsna.util.images;  
  2   
  3 import java.awt.Color;  
  4 import java.awt.Font;  
  5 import java.awt.Graphics2D;  
  6 import java.awt.image.BufferedImage;  
  7 import java.io.FileOutputStream;  
  8 import java.io.IOException;  
  9 import java.io.OutputStream;  
 10 import java.util.Random;  
 11   
 12 import javax.imageio.ImageIO;  
 13 /** 
 14  * 验证码生成器 
 15  * @author dsna 
 16  * 
 17  */  
 18 public class ValidateCode {  
 19     // 图片的宽度。  
 20     private int width = 160;  
 21     // 图片的高度。  
 22     private int height = 40;  
 23     // 验证码字符个数  
 24     private int codeCount = 5;  
 25     // 验证码干扰线数  
 26     private int lineCount = 150;  
 27     // 验证码  
 28     private String code = null;  
 29     // 验证码图片Buffer  
 30     private BufferedImage buffImg=null;  
 31   
 32     private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',  
 33             'K', 'L', 'M', 'N',  'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',  
 34             'X', 'Y', 'Z',  '1', '2', '3', '4', '5', '6', '7', '8', '9' };  
 35   
 36     public  ValidateCode() {  
 37         this.createCode();  
 38     }  
 39   
 40     /** 
 41      *  
 42      * @param width 图片宽 
 43      * @param height 图片高 
 44      */  
 45     public  ValidateCode(int width,int height) {  
 46         this.width=width;  
 47         this.height=height;  
 48         this.createCode();  
 49     }  
 50     /** 
 51      *  
 52      * @param width 图片宽 
 53      * @param height 图片高 
 54      * @param codeCount 字符个数 
 55      * @param lineCount 干扰线条数 
 56      */  
 57     public  ValidateCode(int width,int height,int codeCount,int lineCount) {  
 58         this.width=width;  
 59         this.height=height;  
 60         this.codeCount=codeCount;  
 61         this.lineCount=lineCount;  
 62         this.createCode();  
 63     }  
 64       
 65     public void createCode() {  
 66         int x = 0,fontHeight=0,codeY=0;  
 67         int red = 0, green = 0, blue = 0;  
 68           
 69         x = width / (codeCount +2);//每个字符的宽度  
 70         fontHeight = height - 2;//字体的高度  
 71         codeY = height - 4;  
 72           
 73         // 图像buffer  
 74         buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
 75         Graphics2D g = buffImg.createGraphics();  
 76         // 生成随机数  
 77         Random random = new Random();  
 78         // 将图像填充为白色  
 79         g.setColor(Color.WHITE);  
 80         g.fillRect(0, 0, width, height);  
 81         // 创建字体  
 82         ImgFontByte imgFont=new ImgFontByte();  
 83         Font font =imgFont.getFont(fontHeight);  
 84         g.setFont(font);  
 85           
 86         for (int i = 0; i < lineCount; i++) {  
 87             int xs = random.nextInt(width);  
 88             int ys = random.nextInt(height);  
 89             int xe = xs+random.nextInt(width/8);  
 90             int ye = ys+random.nextInt(height/8);  
 91             red = random.nextInt(255);  
 92             green = random.nextInt(255);  
 93             blue = random.nextInt(255);  
 94             g.setColor(new Color(red, green, blue));  
 95             g.drawLine(xs, ys, xe, ye);  
 96         }  
 97           
 98         // randomCode记录随机产生的验证码  
 99         StringBuffer randomCode = new StringBuffer();  
100         // 随机产生codeCount个字符的验证码。  
101         for (int i = 0; i < codeCount; i++) {  
102             String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);  
103             // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。  
104             red = random.nextInt(255);  
105             green = random.nextInt(255);  
106             blue = random.nextInt(255);  
107             g.setColor(new Color(red, green, blue));  
108             g.drawString(strRand, (i + 1) * x, codeY);  
109             // 将产生的四个随机数组合在一起。  
110             randomCode.append(strRand);  
111         }  
112         // 将四位数字的验证码保存到Session中。  
113         code=randomCode.toString();       
114     }  
115       
116     public void write(String path) throws IOException {  
117         OutputStream sos = new FileOutputStream(path);  
118             this.write(sos);  
119     }  
120       
121     public void write(OutputStream sos) throws IOException {  
122             ImageIO.write(buffImg, "png", sos);  
123             sos.close();  
124     }  
125     public BufferedImage getBuffImg() {  
126         return buffImg;  
127     }  
128       
129     public String getCode() {  
130         return code;  
131     }  
132 }  
ValidateCode.java验证码生成类
 1 package cn.dsna.util.images;  
 2 import java.io.ByteArrayInputStream;  
 3 import java.awt.*;  
 4 /** 
 5  * ttf字体文件 
 6  * @author dsna 
 7  * 
 8  */  
 9 public class ImgFontByte {  
10     public Font getFont(int fontHeight){  
11         try {  
12             Font baseFont = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(hex2byte(getFontByteStr())));  
13             return baseFont.deriveFont(Font.PLAIN, fontHeight);  
14         } catch (Exception e) {  
15             return new Font("Arial",Font.PLAIN, fontHeight);  
16         }  
17     }  
18       
19     private  byte[] hex2byte(String str) {   
20         if (str == null)  
21             return null;  
22         str = str.trim();  
23         int len = str.length();  
24         if (len == 0 || len % 2 == 1)  
25             return null;  
26   
27         byte[] b = new byte[len / 2];  
28         try {  
29             for (int i = 0; i < str.length(); i += 2) {  
30                 b[i / 2] = (byte) Integer  
31                         .decode("0x" + str.substring(i, i + 2)).intValue();  
32             }  
33             return b;  
34         } catch (Exception e) {  
35             return null;  
36         }  
37     } /** 
38   * ttf字体文件的十六进制字符串 
39   * @return 
40   */  
41  private String getFontByteStr(){ return null;  
42         return str;//字符串太长 在附件中找  
43 }  
44 }  
ImgFontByte.java代码
 1 package cn.dsna.util.images;  
 2   
 3 import java.io.IOException;  
 4 import javax.servlet.ServletException;  
 5 import javax.servlet.http.HttpServlet;  
 6 import javax.servlet.http.HttpServletRequest;  
 7 import javax.servlet.http.HttpServletResponse;  
 8 import javax.servlet.http.HttpSession;  
 9   
10 public class ValidateCodeServlet extends HttpServlet {  
11     private static final long serialVersionUID = 1L;  
12   
13     @Override  
14     protected void doGet(HttpServletRequest reqeust,  
15             HttpServletResponse response) throws ServletException, IOException {  
16         // 设置响应的类型格式为图片格式  
17         response.setContentType("image/jpeg");  
18         //禁止图像缓存。  
19         response.setHeader("Pragma", "no-cache");  
20         response.setHeader("Cache-Control", "no-cache");  
21         response.setDateHeader("Expires", 0);  
22           
23         HttpSession session = reqeust.getSession();  
24           
25         ValidateCode vCode = new ValidateCode(120,40,5,100);  
26         session.setAttribute("code", vCode.getCode());  
27         vCode.write(response.getOutputStream());  
28     }  
29 /** 
30  * web.xml 添加servlet 
31     <servlet> 
32         <servlet-name>validateCodeServlet</servlet-name> 
33         <servlet-class>cn.dsna.util.images.ValidateCodeServlet</servlet-class> 
34     </servlet>     
35     <servlet-mapping> 
36         <servlet-name>validateCodeServlet</servlet-name> 
37         <url-pattern>*.images</url-pattern> 
38     </servlet-mapping> 
39  
40 在地址栏输入XXX/dsna.images 测试 
41  */  
42   
43 } 
ValidateCodeServlet.java Servlet调用方法
 1 package cn.dsna.util.images;  
 2   
 3 import java.io.IOException;  
 4 import java.util.Date;  
 5   
 6 public class ValidateCodeTest {  
 7   
 8     /** 
 9      * @param args 
10      */  
11     public static void main(String[] args) {  
12         ValidateCode vCode = new ValidateCode(120,40,5,100);  
13         try {  
14             String path="D:/t/"+new Date().getTime()+".png";  
15             System.out.println(vCode.getCode()+" >"+path);  
16             vCode.write(path);  
17         } catch (IOException e) {  
18             e.printStackTrace();  
19         }  
20     }  
21   
22 } 
ValidateCodeTest.java代码
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>  
web.xml代码

dsnaValidateCode.jar (30.4 KB)

dsnaValidateCode_src.rar (27.5 KB)


来源网站:http://dsna.iteye.com/blog/573456


 

posted @ 2018-08-09 21:30  xiaostudy  阅读(1788)  评论(0编辑  收藏  举报
网站推荐
[理工最爱]小时百科 |  GitHub |  Gitee |  开源中国社区 |  牛客网 |  不学网论坛 |  r2coding |  冷熊简历 |  爱盘 |  零散坑 |  bootstrap中文网 |  vue.js官网教程 |  源码分享站 |  maven仓库 |  楼教主网站 |  廖雪峰网站 |  w3cschool |  在线API |  代码在线运行 |  [不学网]代码在线运行 |  JS在线运行 |  PHP中文网 |  深度开源eclipse插件 |  文字在线加密解密 |  菜鸟教程 |  慕课网 |  千图网 |  手册网 |  素材兔 |  盘多多 |  悦书PDF |  sumatra PDF |  calibre PDF |  Snipaste截图 |  shareX截图 |  vlc-media-player播放器 |  MCMusic player |  IDM下载器 |  格式工厂 |  插件网 |  谷歌浏览器插件 |  Crx搜搜 |  懒人在线计算器 |  leetcode算法题库 |  layer官网 |  layui官网 |  formSelects官网 |  Fly社区 |  程序员客栈 |  融云 |  华为云 |  阿里云 |  ztree官网API |  teamviewer官网 |  sonarlint官网 |  editormd |  pcmark10官网 |  crx4chrome官网 |  apipost官网 |  花生壳官网 |  serv-u官网 |  杀毒eset官网 |  分流抢票bypass官网 |  懒猴子CG代码生成器官网 |  IT猿网 |  natapp[内网穿透] |  ngrok[内网穿透] |  深蓝穿透[内网穿透] |  WakeMeOnLan[查看ip] |  iis7 |  [漏洞扫描]Dependency_Check官网 |  [图标UI]fontawesome官网 |  idea插件官网 |  路过图床官网 |  sha256在线解密 |  在线正则表达式测试 |  在线文件扫毒 |  KuangStudy | 
资源下载
电脑相关: Windows原装下载msdn我告诉你 |  U盘制作微PE工具官网下载 |  Linux_CentOS官网下载 |  Linux_Ubuntu官网下载 |  Linux_OpenSUSE官网下载 |  IE浏览器官网下载 |  firefox浏览器官网下载 |  百分浏览器官网下载 |  谷歌google浏览器历史版本下载 |  深度deepin系统官网下载 |  中兴新支点操作系统官网下载 |  文件对比工具Beyond Compare官网下载 |  开机启动程序startup-delayer官网下载 |  openoffice官网下载 |  utorrent官网下载 |  qbittorrent官网下载 |  cpu-z官网下载 |  蜘蛛校色仪displaycal官网下载 |  单文件制作greenone下载 |  win清理工具Advanced SystemCare官网下载 |  解压bandizip官网下载 |  内存检测工具memtest官网下载 |  磁盘坏道检测与修复DiskGenius官网下载 |  磁盘占用可视化SpaceSniffer官网下载 |  [磁盘可视化]WizTree官网下载 |  win快速定位文件Everything官网下载 |  文件定位listary官网下载 |  动图gifcam官网下载 |  7-Zip官网下载 |  磁盘分区工具diskgenius官网下载 |  CEB文件查看工具Apabi Reader官网下载 |  罗技鼠标options官网下载 |  [去除重复文件]doublekiller官网下载 | 
编程相关: ApacheServer官网下载 |  Apache官网下载 |  Git官网下载 |  Git高速下载 |  Jboss官网下载 |  Mysql官网下载 |  Mysql官网历史版本下载 |  NetBeans IDE官网下载 |  Spring官网下载 |  Nginx官网下载 |  Resin官网下载 |  Tomcat官网下载 |  jQuery历史版本下载 |  nosql官网下载 |  mongodb官网下载 |  mongodb_linux历史版本下载 |  mongodb客户端下载 |  VScode官网下载 |  cxf官网下载 |  maven官网下载 |  QT官网下载 |  SVN官网下载 |  SVN历史版本下载 |  nodeJS官网下载 |  oracle官网下载 |  jdk官网下载 |  STS官网下载 |  STS历史版本官网下载 |  vue官网下载 |  virtualbox官网下载 |  docker desktop官网下载 |  github desktop官网下载 |  EditPlus官网下载 |  zTree下载 |  layui官网下载 |  jqgrid官网下载 |  jqueryui官网下载 |  solr历史版本下载 |  solr分词器ik-analyzer-solr历史版本下载 |  zookeeper历史版本官网下载 |  nssm官网下载 |  elasticsearch官网下载 |  elasticsearch历史版本官网下载 |  redis官网下载 |  redis历史版本官网下载 |  redis的win版本下载 |  putty官网下载 |  查看svn密码TSvnPD官网下载 |  MongoDB连接工具Robo官网下载 |  dll查看exescope官网下载 |  dll2c官网下载 |  接口测试apipost官网下载 |  接口测试postman官网下载 |  原型设计工具AxureRP官网下载 |  canal官网下载 |  idea主题样式下载 |  vue的GitHub下载 |  finalShell官网下载 |  ETL工具kafka官网下载 |  cavaj[java反编译]官网下载 |  jd-gui[java反编译]官网下载 |  radmin[远程连接]官网下载 |  tcping[win ping端口]下载 |  jQueryUploadFile官网下载 |  RedisPlus下载 |  aiXcoder智能编程助手官网下载 |  [表单效验]validform官网下载 |  idea官网下载 |  RedisStudio下载 |  MD转word含公式pandoc官网下载 |  logviewer官网下载 |  Kafka官网下载 |  hbase高速下载 |  hadoop官网下载 |  hadooponwindows的GitHub下载 |  hive官网下载 |  soapui官网下载 |  flink官网下载 |  kafkatool官网下载 |  MinIO官网下载 |  MinIO中国镜像下载 | 
办公相关工具
免费在线拆分PDF【不超过30M】 |  免费在线PDF转Word【不超过10M】 |  在线文字识别转换【不超过1M】 |  PDF转换成Word【不超过50M】 |  在线OCR识别 |  Smallpdf |  文件转换器Convertio |  迅捷PDF转换器 |  字母大小写转换工具 |  档铺 |  快传airportal[可文字] |  快传-文叔叔 |  P2P-小鹿快传 |  [图床]ImgURL | 
网站入口
腾讯文档 |  有道云笔记网页版 |  为知笔记网页版 |  印象笔记网页版 |  蓝奏云 |  QQ邮箱 |  MindMaster在线思维导图 |  bilibili |  PDM文件在线打开 |  MPP文件在线打开 |  在线PS软件 |  在线WPS |  阿里云企业邮箱登陆入口 | 
其他
PDF转换 |  悦书PDF转换 |  手机号注册查询 |  Reg007 |  akmsg |  ip8_ip查询 |  ipip_ip查询 |  天体运行testtubegames |  测试帧率 |  在线网速测试 |