功能強大的驗證碼的Java類庫:Patchca

jopen 10年前發布 | 138K 次閱讀 Patchca 驗證碼(Captcha)

Patchca是Piotr Piastucki寫的一個java驗證碼開源庫,打包成jar文件發布,patchca使用簡單但功能強大。

本例實現了自定義背景,由于生成圖片較小,波動太大時會導致部分文字顯示不全,所以更改了濾鏡屬性。

效果圖:

功能強大的驗證碼的Java類庫:Patchca

代碼如下:

     package com.ninemax.cul.servlet;  



    import java.awt.Color;  

    import java.awt.Graphics;  

    import java.awt.image.BufferedImage;  

    import java.awt.image.BufferedImageOp;  

    import java.io.IOException;  

    import java.io.OutputStream;  

    import java.util.ArrayList;  

    import java.util.List;  

    import java.util.Random;  



    import javax.imageio.ImageIO;  

    import javax.servlet.ServletException;  

    import javax.servlet.http.HttpServlet;  

    import javax.servlet.http.HttpServletRequest;  

    import javax.servlet.http.HttpServletResponse;  

    import javax.servlet.http.HttpSession;  



    import org.patchca.background.BackgroundFactory;  

    import org.patchca.color.ColorFactory;  

    import org.patchca.color.RandomColorFactory;  

    import org.patchca.filter.ConfigurableFilterFactory;  

    import org.patchca.filter.library.AbstractImageOp;  

    import org.patchca.filter.library.WobbleImageOp;  

    import org.patchca.font.RandomFontFactory;  

    import org.patchca.service.Captcha;  

    import org.patchca.service.ConfigurableCaptchaService;  

    import org.patchca.text.renderer.BestFitTextRenderer;  

    import org.patchca.text.renderer.TextRenderer;  

    import org.patchca.word.RandomWordFactory;  



    /**  

     * 驗證碼生成類  

     *  

     * 使用開源驗證碼項目patchca生成  

     * 依賴jar包:patchca-0.5.0.jar  

     * 項目網址:https://code.google.com/p/patchca/  

     *  

     * @author zyh 

     * @version 1.00  2012-7-12 New  

     */  

    public class ValidationCodeServlet extends HttpServlet {  

        private static final long serialVersionUID = 5126616339795936447L;  



        private ConfigurableCaptchaService configurableCaptchaService = null;  

        private ColorFactory colorFactory = null;  

        private RandomFontFactory fontFactory = null;  

        private RandomWordFactory wordFactory = null;  

        private TextRenderer textRenderer = null;  



        public ValidationCodeServlet() {  

            super();  

        }  



        /** 

         * Servlet銷毀方法,負責銷毀所使用資源. <br> 

         */  

        public void destroy() {  

            wordFactory = null;  

            colorFactory = null;  

            fontFactory = null;  

            textRenderer = null;  

            configurableCaptchaService = null;  

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

        }  



        public void doGet(HttpServletRequest request, HttpServletResponse response)  

                throws ServletException, IOException {  

            doPost(request, response);  

        }  



        public void doPost(HttpServletRequest request, HttpServletResponse response)  

                throws ServletException, IOException {  

            response.setContentType("image/png");  

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



            HttpSession session = request.getSession(true);  

            OutputStream outputStream = response.getOutputStream();  



            // 得到驗證碼對象,有驗證碼圖片和驗證碼字符串  

            Captcha captcha = configurableCaptchaService.getCaptcha();  

            // 取得驗證碼字符串放入Session  

            String validationCode = captcha.getChallenge();  

            session.setAttribute("validationCode", validationCode);  

            // 取得驗證碼圖片并輸出  

            BufferedImage bufferedImage = captcha.getImage();  

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



            outputStream.flush();  

            outputStream.close();  

        }  



        /** 

         * Servlet初始化方法 

         */  

        public void init() throws ServletException {  

            configurableCaptchaService = new ConfigurableCaptchaService();  



            // 顏色創建工廠,使用一定范圍內的隨機色  

            colorFactory = new RandomColorFactory();  

            configurableCaptchaService.setColorFactory(colorFactory);  



            // 隨機字體生成器  

            fontFactory = new RandomFontFactory();  

            fontFactory.setMaxSize(32);  

            fontFactory.setMinSize(28);  

            configurableCaptchaService.setFontFactory(fontFactory);  



            // 隨機字符生成器,去除掉容易混淆的字母和數字,如o和0等  

            wordFactory = new RandomWordFactory();  

            wordFactory.setCharacters("abcdefghkmnpqstwxyz23456789");  

            wordFactory.setMaxLength(5);  

            wordFactory.setMinLength(4);  

            configurableCaptchaService.setWordFactory(wordFactory);  



            // 自定義驗證碼圖片背景  

            MyCustomBackgroundFactory backgroundFactory = new MyCustomBackgroundFactory();  

            configurableCaptchaService.setBackgroundFactory(backgroundFactory);  



            // 圖片濾鏡設置  

            ConfigurableFilterFactory filterFactory = new ConfigurableFilterFactory();  



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

            WobbleImageOp wobbleImageOp = new WobbleImageOp();  

            wobbleImageOp.setEdgeMode(AbstractImageOp.EDGE_MIRROR);  

            wobbleImageOp.setxAmplitude(2.0);  

            wobbleImageOp.setyAmplitude(1.0);  

            filters.add(wobbleImageOp);  

            filterFactory.setFilters(filters);  



            configurableCaptchaService.setFilterFactory(filterFactory);  



            // 文字渲染器設置  

            textRenderer = new BestFitTextRenderer();  

            textRenderer.setBottomMargin(3);  

            textRenderer.setTopMargin(3);  

            configurableCaptchaService.setTextRenderer(textRenderer);  



            // 驗證碼圖片的大小  

            configurableCaptchaService.setWidth(82);  

            configurableCaptchaService.setHeight(32);  

        }  



        /** 

         * 自定義驗證碼圖片背景,主要畫一些噪點和干擾線 

         */  

        private class MyCustomBackgroundFactory implements BackgroundFactory {  

            private Random random = new Random();  



            public void fillBackground(BufferedImage image) {  

                Graphics graphics = image.getGraphics();  



                // 驗證碼圖片的寬高  

                int imgWidth = image.getWidth();  

                int imgHeight = image.getHeight();  



                // 填充為白色背景  

                graphics.setColor(Color.WHITE);  

                graphics.fillRect(0, 0, imgWidth, imgHeight);  



                // 畫100個噪點(顏色及位置隨機)  

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

                    // 隨機顏色  

                    int rInt = random.nextInt(255);  

                    int gInt = random.nextInt(255);  

                    int bInt = random.nextInt(255);  



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



                    // 隨機位置  

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

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



                    // 隨機旋轉角度  

                    int sAngleInt = random.nextInt(360);  

                    int eAngleInt = random.nextInt(360);  



                    // 隨機大小  

                    int wInt = random.nextInt(6);  

                    int hInt = random.nextInt(6);  



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



                    // 畫5條干擾線  

                    if (i % 20 == 0) {  

                        int xInt2 = random.nextInt(imgWidth);  

                        int yInt2 = random.nextInt(imgHeight);  

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

                    }  

                }  

            }  

        }  

    }  

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

     <servlet>  

        <servlet-name>validationCode</servlet-name>  

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

      </servlet>  



      <servlet-mapping>  

        <servlet-name>validationCode</servlet-name>  

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

      </servlet-mapping>  
JSP引用(部分):
     <img id="validationCode" alt="驗證碼圖片" title="驗證碼圖片" src="<%=path %>/validationCodeServlet.png" onclick="refreshCode(this)" />  

    <a id="aRecode" href="javascript:void(0);" onclick="refreshCode()">換一張</a>  
JS重新載入圖片方法(參考):
     /** 

     * 刷新驗證碼 

     * @param imgObj 驗證碼Img元素 

     */  

    function refreshCode(imgObj) {  

        if (!imgObj) {  

            imgObj = document.getElementById("validationCode");  

        }  

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

        if(index != -1) {  

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

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

        } else {  

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

        }  

    }  

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!