Patchca是Piotr Piastucki寫的一個java驗證碼開源庫,打包成jar文件發佈,patchca使用簡單但功能強大。javascript
本例實現了自定義背景,因爲生成圖片較小,波動太大時會致使部分文字顯示不全,因此更改了濾鏡屬性。
html
效果圖:java
代碼以下:web
[java] view plaincopysession
package com.ninemax.cul.servlet; app
import java.awt.Color; dom
import java.awt.Graphics; 字體
import java.awt.image.BufferedImage; this
import java.awt.image.BufferedImageOp; google
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配置以下:
[html] view plaincopy
<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引用(部分):
[html] view plaincopy
<img id="validationCode" alt="驗證碼圖片" title="驗證碼圖片" src="<%=path %>/validationCodeServlet.png" onclick="refreshCode(this)" />
<a id="aRecode" href="javascript:void(0);" onclick="refreshCode()">換一張</a>
JS從新載入圖片方法(參考):
[javascript] view plaincopy
/**
* 刷新驗證碼
* @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();
}
}