Patchca是Piotr Piastucki寫的一個java驗證碼開源庫,打包成jar檔案發布,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();// 取得驗證碼字串放入SessionString 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();}}