依赖包:
captcha1.0.jar 包是我自己打的maven中找不到的。
下载地址:https://pan.baidu.com/s/1o8Dr2nK
使用方式:
动态图:
/**
* @Title:获取验证码图片(Gif版本)
* @Description:返回图片流到response中
* @author 张颖辉
* @date 2017年1月4日上午10:10:30
* @param request
* @param response
*/
@RequestMapping(value="getGifVerifyCode2Stream",method=RequestMethod.GET)
public void getGifVerifyCode2Stream(Integer w,Integer h,HttpServletResponse response,HttpServletRequest request){
try {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/gif");
/**
* gif格式动画验证码
* 宽,高,位数。
*/
// 生成图片
w=w==null?200:w;
h=h==null?80:h;
Captcha captcha = new GifCaptcha(w,h,4);
//输出
captcha.out(response.getOutputStream());
HttpSession session = request.getSession(true);
//存入Session
session.setAttribute("pic_verifyCode",captcha.text().toLowerCase());
} catch (Exception e) {
//LoggerUtils.fmtError(getClass(),e, "获取验证码异常:%s",e.getMessage());
logger.error("生成验证码动态图片失败", e);
}
}
效果:
静态图:
/**
* @Title:获取验证码图片(jpg版本)
* @Description:返回图片流到response中
* @author 张颖辉
* @date 2017年1月4日上午10:10:30
* @param request
* @param response
*/
@RequestMapping(value = "getJpgVerifyCode2Stream", method = RequestMethod.GET)
public void getJpgVerifyCode2Stream(Integer w, Integer h, HttpServletResponse response, HttpServletRequest request) {
try {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpg");
// 生成图片
w = w == null ? 200 : w;
h = h == null ? 80 : h;
Captcha captcha = new SpecCaptcha(w, h, 4);
// 输出
captcha.out(response.getOutputStream());
// 存入Session
HttpSession session = request.getSession(true);
session.setAttribute("pic_verifyCode", captcha.text().toLowerCase());
} catch (Exception e) {
logger.error("生成验证码图片(白底)失败", e);
}
}
效果:
参考:http://www.sojson.com/blog/71.html