Java里使用patchca生成验证码

Patchca是Piotr Piastucki写的一个java验证码开源库,打包成jar文件发布,patchca使用简单但功能强大。

本例实现了自定义背景,由于生成图片较小,波动太大时会导致部分文字显示不全,所以更改了滤镜属性。

效果图:

代码如下:

[java] view plaincopy

  1. package com.ninemax.cul.servlet;  

  2.   

  3. import java.awt.Color;  

  4. import java.awt.Graphics;  

  5. import java.awt.image.BufferedImage;  

  6. import java.awt.image.BufferedImageOp;  

  7. import java.io.IOException;  

  8. import java.io.OutputStream;  

  9. import java.util.ArrayList;  

  10. import java.util.List;  

  11. import java.util.Random;  

  12.   

  13. import javax.imageio.ImageIO;  

  14. import javax.servlet.ServletException;  

  15. import javax.servlet.http.HttpServlet;  

  16. import javax.servlet.http.HttpServletRequest;  

  17. import javax.servlet.http.HttpServletResponse;  

  18. import javax.servlet.http.HttpSession;  

  19.   

  20. import org.patchca.background.BackgroundFactory;  

  21. import org.patchca.color.ColorFactory;  

  22. import org.patchca.color.RandomColorFactory;  

  23. import org.patchca.filter.ConfigurableFilterFactory;  

  24. import org.patchca.filter.library.AbstractImageOp;  

  25. import org.patchca.filter.library.WobbleImageOp;  

  26. import org.patchca.font.RandomFontFactory;  

  27. import org.patchca.service.Captcha;  

  28. import org.patchca.service.ConfigurableCaptchaService;  

  29. import org.patchca.text.renderer.BestFitTextRenderer;  

  30. import org.patchca.text.renderer.TextRenderer;  

  31. import org.patchca.word.RandomWordFactory;  

  32.   

  33. /**  

  34.  * 验证码生成类  

  35.  *  

  36.  * 使用开源验证码项目patchca生成  

  37.  * 依赖jar包:patchca-0.5.0.jar  

  38.  * 项目网址:https://code.google.com/p/patchca/  

  39.  *  

  40.  * @author zyh 

  41.  * @version 1.00  2012-7-12 New  

  42.  */  

  43. public class ValidationCodeServlet extends HttpServlet {  

  44.     private static final long serialVersionUID = 5126616339795936447L;  

  45.       

  46.     private ConfigurableCaptchaService configurableCaptchaService = null;  

  47.     private ColorFactory colorFactory = null;  

  48.     private RandomFontFactory fontFactory = null;  

  49.     private RandomWordFactory wordFactory = null;  

  50.     private TextRenderer textRenderer = null;  

  51.       

  52.     public ValidationCodeServlet() {  

  53.         super();  

  54.     }  

  55.   

  56.     /** 

  57.      * Servlet销毁方法,负责销毁所使用资源. <br> 

  58.      */  

  59.     public void destroy() {  

  60.         wordFactory = null;  

  61.         colorFactory = null;  

  62.         fontFactory = null;  

  63.         textRenderer = null;  

  64.         configurableCaptchaService = null;  

  65.         super.destroy(); // Just puts "destroy" string in log  

  66.     }  

  67.   

  68.     public void doGet(HttpServletRequest request, HttpServletResponse response)  

  69.             throws ServletException, IOException {  

  70.         doPost(request, response);  

  71.     }  

  72.   

  73.     public void doPost(HttpServletRequest request, HttpServletResponse response)  

  74.             throws ServletException, IOException {  

  75.         response.setContentType("image/png");  

  76.         response.setHeader("cache""no-cache");  

  77.           

  78.         HttpSession session = request.getSession(true);  

  79.         OutputStream outputStream = response.getOutputStream();  

  80.           

  81.         // 得到验证码对象,有验证码图片和验证码字符串  

  82.         Captcha captcha = configurableCaptchaService.getCaptcha();  

  83.         // 取得验证码字符串放入Session  

  84.         String validationCode = captcha.getChallenge();  

  85.         session.setAttribute("validationCode", validationCode);  

  86.         // 取得验证码图片并输出  

  87.         BufferedImage bufferedImage = captcha.getImage();  

  88.         ImageIO.write(bufferedImage, "png", outputStream);  

  89.           

  90.         outputStream.flush();  

  91.         outputStream.close();  

  92.     }  

  93.   

  94.     /** 

  95.      * Servlet初始化方法 

  96.      */  

  97.     public void init() throws ServletException {  

  98.         configurableCaptchaService = new ConfigurableCaptchaService();  

  99.           

  100.         // 颜色创建工厂,使用一定范围内的随机色  

  101.         colorFactory = new RandomColorFactory();  

  102.         configurableCaptchaService.setColorFactory(colorFactory);  

  103.           

  104.         // 随机字体生成器  

  105.         fontFactory = new RandomFontFactory();  

  106.         fontFactory.setMaxSize(32);  

  107.         fontFactory.setMinSize(28);  

  108.         configurableCaptchaService.setFontFactory(fontFactory);  

  109.           

  110.         // 随机字符生成器,去除掉容易混淆的字母和数字,如o和0等  

  111.         wordFactory = new RandomWordFactory();  

  112.         wordFactory.setCharacters("abcdefghkmnpqstwxyz23456789");  

  113.         wordFactory.setMaxLength(5);  

  114.         wordFactory.setMinLength(4);  

  115.         configurableCaptchaService.setWordFactory(wordFactory);  

  116.           

  117.         // 自定义验证码图片背景  

  118.         MyCustomBackgroundFactory backgroundFactory = new MyCustomBackgroundFactory();  

  119.         configurableCaptchaService.setBackgroundFactory(backgroundFactory);  

  120.           

  121.         // 图片滤镜设置  

  122.         ConfigurableFilterFactory filterFactory = new ConfigurableFilterFactory();  

  123.           

  124.         List<BufferedImageOp> filters = new ArrayList<BufferedImageOp>();  

  125.         WobbleImageOp wobbleImageOp = new WobbleImageOp();  

  126.         wobbleImageOp.setEdgeMode(AbstractImageOp.EDGE_MIRROR);  

  127.         wobbleImageOp.setxAmplitude(2.0);  

  128.         wobbleImageOp.setyAmplitude(1.0);  

  129.         filters.add(wobbleImageOp);  

  130.         filterFactory.setFilters(filters);  

  131.           

  132.         configurableCaptchaService.setFilterFactory(filterFactory);  

  133.           

  134.         // 文字渲染器设置  

  135.         textRenderer = new BestFitTextRenderer();  

  136.         textRenderer.setBottomMargin(3);  

  137.         textRenderer.setTopMargin(3);  

  138.         configurableCaptchaService.setTextRenderer(textRenderer);  

  139.           

  140.         // 验证码图片的大小  

  141.         configurableCaptchaService.setWidth(82);  

  142.         configurableCaptchaService.setHeight(32);  

  143.     }  

  144.       

  145.     /** 

  146.      * 自定义验证码图片背景,主要画一些噪点和干扰线 

  147.      */  

  148.     private class MyCustomBackgroundFactory implements BackgroundFactory {  

  149.         private Random random = new Random();  

  150.   

  151.         public void fillBackground(BufferedImage image) {  

  152.             Graphics graphics = image.getGraphics();  

  153.               

  154.             // 验证码图片的宽高  

  155.             int imgWidth = image.getWidth();  

  156.             int imgHeight = image.getHeight();  

  157.               

  158.             // 填充为白色背景  

  159.             graphics.setColor(Color.WHITE);  

  160.             graphics.fillRect(00, imgWidth, imgHeight);  

  161.               

  162.             // 画100个噪点(颜色及位置随机)  

  163.             for(int i = 0; i < 100; i++) {  

  164.                 // 随机颜色  

  165.                 int rInt = random.nextInt(255);  

  166.                 int gInt = random.nextInt(255);  

  167.                 int bInt = random.nextInt(255);  

  168.                   

  169.                 graphics.setColor(new Color(rInt, gInt, bInt));  

  170.                   

  171.                 // 随机位置  

  172.                 int xInt = random.nextInt(imgWidth - 3);  

  173.                 int yInt = random.nextInt(imgHeight - 2);  

  174.                   

  175.                 // 随机旋转角度  

  176.                 int sAngleInt = random.nextInt(360);  

  177.                 int eAngleInt = random.nextInt(360);  

  178.                   

  179.                 // 随机大小  

  180.                 int wInt = random.nextInt(6);  

  181.                 int hInt = random.nextInt(6);  

  182.                   

  183.                 graphics.fillArc(xInt, yInt, wInt, hInt, sAngleInt, eAngleInt);  

  184.                   

  185.                 // 画5条干扰线  

  186.                 if (i % 20 == 0) {  

  187.                     int xInt2 = random.nextInt(imgWidth);  

  188.                     int yInt2 = random.nextInt(imgHeight);  

  189.                     graphics.drawLine(xInt, yInt, xInt2, yInt2);  

  190.                 }  

  191.             }  

  192.         }  

  193.     }  

  194. }  

由于是个Servlet所以web.xml配置如下:

[html] view plaincopy

  1. <servlet>  

  2.     <servlet-name>validationCode</servlet-name>  

  3.     <servlet-class>com.ninemax.cul.servlet.ValidationCodeServlet</servlet-class>  

  4.   </servlet>  

  5.   

  6.   <servlet-mapping>  

  7.     <servlet-name>validationCode</servlet-name>  

  8.     <url-pattern>/validationCodeServlet.png</url-pattern>  

  9.   </servlet-mapping>  


JSP引用(部分):

[html] view plaincopy

  1. <img id="validationCode" alt="验证码图片" title="验证码图片" src="<%=path %>/validationCodeServlet.png" onclick="refreshCode(this)" />  

  2. <a id="aRecode" href="javascript:void(0);" onclick="refreshCode()">换一张</a>  


JS重新载入图片方法(参考):

[javascript] view plaincopy

  1. /** 

  2.  * 刷新验证码 

  3.  * @param imgObj 验证码Img元素 

  4.  */  

  5. function refreshCode(imgObj) {  

  6.     if (!imgObj) {  

  7.         imgObj = document.getElementById("validationCode");  

  8.     }  

  9.     var index = imgObj.src.indexOf("?");  

  10.     if(index != -1) {  

  11.         var url = imgObj.src.substring(0,index + 1);  

  12.         imgObj.src = url + Math.random();  

  13.     } else {  

  14.         imgObj.src = imgObj.src + "?" + Math.random();  

  15.     }  

  16. }  


转载于:https://my.oschina.net/easonwang14/blog/222132

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值