java Graphics2D生成图形验证码

最近项目要用到图形验证码,上网查找资料,参考改了一个工具类,并添加到程序中,下面记录下来以做备份,添加了注释,和web页面校验验证码

大概步骤是:

1.在内存中创建缓存图片

2.设置背景色,字体

3.画边框

4.绘制干扰信息

5.写入验证码

6.图片输出

废话不多说,直接上代码

[java]  view plain  copy
  1. package com.jd.jr.faecms.common.validateCode;  
  2.   
  3. import javax.imageio.ImageIO;  
  4. import java.awt.*;  
  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.Date;  
  10. import java.util.Random;  
  11.   
  12. /** 
  13.  * 验证码生成工具类
  14.  * 
  15.  * @leo  
  16.  */  
  17. public class ValidateCode {  
  18.     // 图片的宽度。  
  19.     private int width = 160;  
  20.     // 图片的高度。  
  21.     private int height = 40;  
  22.     // 验证码字符个数  
  23.     private int codeCount = 5;  
  24.     // 验证码干扰线数  
  25.     private int lineCount = 150;  
  26.     // 验证码  
  27.     private String code = null;  
  28.     // 验证码图片Buffer  
  29.     private BufferedImage buffImg = null;  
  30.   
  31.     // 验证码范围,去掉0(数字)和O(拼音)容易混淆的(小写的1和L也可以去掉,大写不用了)  
  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.     /** 
  37.      * 默认构造函数,设置默认参数 
  38.      */  
  39.     public ValidateCode() {  
  40.         this.createCode();  
  41.     }  
  42.   
  43.     /** 
  44.      * @param width  图片宽 
  45.      * @param height 图片高 
  46.      */  
  47.     public ValidateCode(int width, int height) {  
  48.         this.width = width;  
  49.         this.height = height;  
  50.         this.createCode();  
  51.     }  
  52.   
  53.     /** 
  54.      * @param width     图片宽 
  55.      * @param height    图片高 
  56.      * @param codeCount 字符个数 
  57.      * @param lineCount 干扰线条数 
  58.      */  
  59.     public ValidateCode(int width, int height, int codeCount, int lineCount) {  
  60.         this.width = width;  
  61.         this.height = height;  
  62.         this.codeCount = codeCount;  
  63.         this.lineCount = lineCount;  
  64.         this.createCode();  
  65.     }  
  66.   
  67.     public void createCode() {  
  68.         int x = 0, fontHeight = 0, codeY = 0;  
  69.         int red = 0, green = 0, blue = 0;  
  70.   
  71.         x = width / (codeCount + 2);//每个字符的宽度(左右各空出一个字符)  
  72.         fontHeight = height - 2;//字体的高度  
  73.         codeY = height - 4;  
  74.   
  75.         // 图像buffer  
  76.         buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  77.         Graphics2D g = buffImg.createGraphics();        
              
  78.         /*// 将图像背景填充为白色  
  79.         g.setColor(Color.WHITE);  
            g.fillRect(0, 0, width, height);*/
  80.         // 增加下面代码使得背景透明 
            buffImg = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);  
            g.dispose();  
            g = buffImg.createGraphics();  
            // 背景透明代码结束  
              
            // 画图BasicStroke是JDK中提供的一个基本的画笔类,我们对他设置画笔的粗细,就可以在drawPanel上任意画出自己想要的图形了。  
            g.setColor(new Color(255, 0, 0));  
            g.setStroke(new BasicStroke(1f));  
            g.fillRect(128, 128, width, height);
  81.         
  82.         // 生成随机数  
  83.         Random random = new Random();    
  84.                         //设置字体类型、字体大小、字体样式 
                    Font font = new Font("微软雅黑",Font.PLAIN, fontHeight);
  85.   
  86.         g.setFont(font);  
  87.   
  88.         for (int i = 0; i < lineCount; i++) {  
  89.             // 设置随机开始和结束坐标  
  90.             int xs = random.nextInt(width);//x坐标开始  
  91.             int ys = random.nextInt(height);//y坐标开始  
  92.             int xe = xs + random.nextInt(width / 8);//x坐标结束  
  93.             int ye = ys + random.nextInt(height / 8);//y坐标结束  
  94.   
  95.             // 产生随机的颜色值,让输出的每个干扰线的颜色值都将不同。  
  96.             red = random.nextInt(255);  
  97.             green = random.nextInt(255);  
  98.             blue = random.nextInt(255);  
  99.             g.setColor(new Color(red, green, blue));  
  100.             g.drawLine(xs, ys, xe, ye);  
  101.         }  
  102.   
  103.         // randomCode记录随机产生的验证码  
  104.         StringBuffer randomCode = new StringBuffer();  
  105.         // 随机产生codeCount个字符的验证码。  
  106.         for (int i = 0; i < codeCount; i++) {  
  107.             String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);  
  108.             // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。  
  109.             red = random.nextInt(255);  
  110.             green = random.nextInt(255);  
  111.             blue = random.nextInt(255);  
  112.             //指定某种颜色
  113.             //g.setColor(new Color(252, 145, 83));
  114.             g.setColor(new Color(red, green, blue));  
  115.             g.drawString(strRand, (i + 1) * x, codeY);  
  116.             // 将产生的四个随机数组合在一起。  
  117.             randomCode.append(strRand);  
  118.         }  
  119.         // 将四位数字的验证码保存到Session中。  
  120.         code = randomCode.toString();  
  121.     }  
  122.   
  123.     public void write(String path) throws IOException {  
  124.         OutputStream sos = new FileOutputStream(path);  
  125.         this.write(sos);  
  126.     }  
  127.   
  128.     public void write(OutputStream sos) throws IOException {  
  129.         ImageIO.write(buffImg, "png", sos);  
  130.         sos.close();  
  131.     }  
  132.   
  133.     public BufferedImage getBuffImg() {  
  134.         return buffImg;  
  135.     }  
  136.   
  137.     public String getCode() {  
  138.         return code;  
  139.     }  
  140.   
  141.     /** 
  142.      * 测试函数,默认生成到d盘 
  143.      * @param args 
  144.      */  
  145.     public static void main(String[] args) {  
  146.         ValidateCode vCode = new ValidateCode(160,40,5,150);  
  147.         try {  
  148.             String path="D:/"+new Date().getTime()+".png";  
  149.             System.out.println(vCode.getCode()+" >"+path);  
  150.             vCode.write(path);  
  151.         } catch (IOException e) {  
  152.             e.printStackTrace();  
  153.         }  
  154.     }  
  155. }  

下面是页面调用验证码

[html]  view plain  copy
  1. <div class="form-group  col-lg-6">  
  2.     <label for="id" class="col-sm-4 control-label">  
  3.         验证码:  
  4.     </label>  
  5.     <div class="col-sm-8">  
  6.         <input type="text" id="code" name="code" class="form-control" style="width:250px;"/>  
  7.         <img id="imgObj" alt="验证码" src="/article/validateCode" onclick="changeImg()"/>  
  8.         <a href="#" onclick="changeImg()">换一张</a>  
  9.     </div>  
  10. </div>  
  11.   
  12. <script type="text/javascript">  
  13.     // 刷新图片  
  14.     function changeImg() {  
  15.         var imgSrc = $("#imgObj");  
  16.         var src = imgSrc.attr("src");  
  17.         imgSrc.attr("src", changeUrl(src));  
  18.     }  
  19.     //为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳  
  20.     function changeUrl(url) {  
  21.         var timestamp = (new Date()).valueOf();  
  22.         var index = url.indexOf("?",url);  
  23.         if (index > 0) {  
  24.             url = url.substring(0, url.indexOf(url, "?"));  
  25.         }  
  26.         if ((url.indexOf("&") >= 0)) {  
  27.             url = url + "×tamp=" + timestamp;  
  28.         } else {  
  29.             url = url + "?timestamp=" + timestamp;  
  30.         }  
  31.         return url;  
  32.     }  
  33. </script>  


下面是controller层输出验证码

[java]  view plain  copy
  1. /** 
  2.  * 响应验证码页面 
  3.  * @return 
  4.  */  
  5. @RequestMapping(value="/validateCode")  
  6. public String validateCode(HttpServletRequest request,HttpServletResponse response) throws Exception{  
  7.     // 设置响应的类型格式为图片格式  
  8.     response.setContentType("image/jpeg");  
  9.     //禁止图像缓存。  
  10.     response.setHeader("Pragma""no-cache");  
  11.     response.setHeader("Cache-Control""no-cache");  
  12.     response.setDateHeader("Expires"0);  
  13.   
  14.     HttpSession session = request.getSession();  
  15.   
  16.     ValidateCode vCode = new ValidateCode(120,40,5,100);  
  17.     session.setAttribute("code", vCode.getCode());  
  18.     vCode.write(response.getOutputStream());  
  19.     return null;  
  20. }  

下面是controller层验证验证码输入是否正确

[java]  view plain  copy
  1. String code = request.getParameter("code");  
  2. HttpSession session = request.getSession();  
  3. String sessionCode = (String) session.getAttribute("code");  
  4. if (!StringUtils.equalsIgnoreCase(code, sessionCode)) {  //忽略验证码大小写  
  5.     throw new RuntimeException("验证码对应不上code=" + code + "  sessionCode=" + sessionCode);  
  6. }

猜你喜欢

转载自blog.csdn.net/lchq1995/article/details/79424270