Java使用patchca生成验证码

       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();
// 取得验证码字符串放入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.GRAY);
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();
}
}

本文是转载,同时自己亲自测试可行,上面的验证码截图就是实际效果   参考链接:http://blog.csdn.net/zhyh1986/article/details/7741244

同时需要patchca架包:http://download.csdn.net/download/caoniquanjiaariniday/7607495

【java提高】---patchca生成验证码的更多相关文章

  1. 【功能代码】---2.patchca生成验证码

    Java使用patchca生成验证码        Patchca是Piotr Piastucki写的一个java验证码开源库,打包成jar文件发布,patchca使用简单但功能强大. 本例实现了自定 ...

  2. java web,生成验证码图片的技术

    偶然知道原来有些网站的验证码图片都是随机生成的,后来听人讲了一下,就做了这个小例子 生成图片,绘制背景,数字,干扰线用到了java.awt包,主要使用BufferedImage来生成图片,然后使用Gr ...

  3. JAVA整合kaptcha生成验证码 (字母验证码和算术验证码)

    引入maven <!--图片验证码--> <dependency> <groupId>com.github.penggle</groupId> < ...

  4. java自己主动生成验证码

    代码结构: web.xml <? xml version="1.0" encoding="UTF-8"?> <web-app version= ...

  5. Java生成验证码_转

    为了防止用户恶意,或者使用软件外挂提交一些内容,就得用验证码来阻止,虽然这个会影响用户体验,但为了避免一些问题很多网站都使用了验证码;今天下午参考文档弄了一个验证码,这里分享一下;这是一个web工程, ...

  6. java web学习总结(九) -------------------通过Servlet生成验证码图片

    一.BufferedImage类介绍 生成验证码图片主要用到了一个BufferedImage类,如下:

  7. Java生成验证码原理(jsp)

     验证码的作用: 验证码是Completely Automated Public Turing test to tell Computers and Humans Apart(全自动区分计算机和人类的 ...

  8. java web 学习九(通过servlet生成验证码图片)

    一.BufferedImage类介绍 生成验证码图片主要用到了一个BufferedImage类,如下:

  9. 【开发技术】Java生成验证码

    Java生成验证码 为了防止用户恶意,或者使用软件外挂提交一些内容,就得用验证码来阻止,虽然这个会影响用户体验,但为了避免一些问题很多网站都使用了验证码;今天下午参考文档弄了一个验证码,这里分享一下; ...

随机推荐

  1. ABAP 新语法记录(一)

    原文链接:https://www.cnblogs.com/learnning/p/10647174.html 主要内容 内联声明 构造表达式 内表操作 Open SQL 其他 本文列出了ABAP新语法 ...

  2. 动态SQL屏幕条件选择(里面还有赋值的新语法)

    有时候屏幕条件中使用PARAMETERS时候,如果你为空的话,会查不出数据,但是可能你的想法是不想限制而已,但是系统默认理解为了空值,这个时候,如果取判断一下条件是不是空,在SQL里决定写不写的话,会 ...

  3. 动态类型dynamic转换为特定类型T的方案

    需求场景:有时候我们抓到一段请求数据,JSON格式的字符串数据,需要放在接口里重现问题,我们就可能会用dynamic先接受数据,然后再转换成特定数据发出请求. 方案一:直接使用特定对象T,来接受请求数 ...

  4. charAt()检测回文

    package seday01; /** * char charAt(int index) 返回指定位置对应的字符 * @author xingsir */public class CharAtDem ...

  5. 易优CMS:type的基础用法

    [基础用法] 名称:type 功能:获取指定栏目信息 语法: {eyou:type typeid='栏目ID' empty='暂时没有数据'} <a href="{$field.typ ...

  6. FCC---Change Animation Timing with Keywords--两个小球从A都B,相同循环时间 duration, 不同的速度 speed

    In CSS animations, the animation-timing-function property controls how quickly an animated element c ...

  7. iOS----------获取通知状态并跳转设置界面设置

    跳转app对应的系统通知设置 if (UIApplicationOpenSettingsURLString != NULL) { UIApplication *application = [UIApp ...

  8. linux rz sz文件传输 ZModem协议

    比ftp和scp方便点.需要用支持ZModem协议的工具,SecureCRT是可以的 rz: 接收文件 sz: 发送文件 安装 # sudo apt-get install lrzsz 使用 协议介绍 ...

  9. CodeForces 1260D(二分+贪心+差分)

    题意 https://vjudge.net/problem/CodeForces-1260D 有m个士兵,t秒,你要带尽可能多的士兵从0去n+1,且他们不能被杀死.路上有一些陷阱,陷阱d[i]会杀死能 ...

  10. CodeForces - 1228D (暴力+思维+乱搞)

    题意 https://vjudge.net/problem/CodeForces-1228D 有一个n个顶点m条边的无向图,在一对顶点中最多有一条边. 设v1,v2是两个不相交的非空子集,当满足以下条 ...