在项目中经常会见到图片验证码和短信验证码的,小编在最近的项目里负责这部分,那么图片验证码是什么呢?
是什么?
图形验证码是验证码的一种。验证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。
为什么用?
为什么要用图片验证码呢?可以防止:恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。
怎么玩?
1:首先写一个静态工具类:VerificationCodeImgUtil
<strong><span style="font-size:18px;"><span style="font-size:18px;">import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class VerificationCodeImgUtil {
// 图像
private BufferedImage image;
// 验证码
private String str;
// 图像宽度
private int width = 80;
// 图像高度
private int height = 40;
private static final Font FONT = new Font("Consolas", Font.BOLD, 20);
/**
* 功能:获取一个验证码类的实例
*
* @return
*/
public static VerificationCodeImgUtil getInstance() {
return new VerificationCodeImgUtil();
}
public static VerificationCodeImgUtil getInstance(int width, int height) {
return new VerificationCodeImgUtil(width, height);
}
private VerificationCodeImgUtil() {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
private VerificationCodeImgUtil(int width, int height) {
this.width = width;
this.height = height;
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
/**
* 生成图片验证码
* @param code
*/
public void initVerificationCode(String code) {
Random random = new Random(); // 生成随机类
Graphics g = initImage(image, random);
char[] chars = code.toCharArray();
for (int i = 0; i < chars.length; ++i) {
g.setColor(new Color(20 + random.nextInt(10), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(String.valueOf(chars[i]), 13 * i + 16, 26);
}
this.setStr(code);/* 赋值验证码 */
g.dispose(); // 图象生效
}
private Graphics initImage(BufferedImage image, Random random) {
Graphics g = image.getGraphics(); // 获取图形上下文
g.setColor(getRandColor(200, 250));// 设定背景色
g.fillRect(0, 0, width, width);
g.setFont(FONT);// 设定字体
g.setColor(getRandColor(160, 200)); // 随机产生165条干扰线,使图象中的认证码不易被其它程序探测到
for (int i = 0; i < 165; i++) {
int x = random.nextInt(width);
int y = random.nextInt(width);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
return g;
}
/*
* 功能:给定范围获得随机颜色
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
/**
* 功能:获取验证码的字符串值
*
* @return
*/
public String getVerificationCodeValue() {
return this.getStr();
}
/**
* 功能:取得验证码图片
*
* @return
*/
public BufferedImage getImage() {
return this.image;
}
public String getStr() {
return str;
}
private void setStr(String str) {
this.str = str;
}
}</span></span></strong>
2:以restful接口为例,来展示如何生成随机的图片验证码,在生成图片验证码的时候使用的redis缓存来存储图片验证码
<strong><span style="font-size:18px;"> /**
* 图片验证码
*
* @return
*/
@RequestMapping(value = "/captcha", method = { RequestMethod.GET })
@ApiOperation(value = "获取图片验证码")
public void captcha(@RequestParam(value = "captchaType") Integer captchaType,
@RequestParam(value = "channelId", required = true) String channelId) {
long customerId = getMemberId();
try {
String code = RandomStringUtils.randomAlphanumeric(4);
// 生成验证码图片
VerificationCodeImgUtil verificationCodeImgUtil = VerificationCodeImgUtil.getInstance(72, 42);
verificationCodeImgUtil.initVerificationCode(code);
// 设置响应类型
response.setContentType("image/jpeg");
response.addHeader("Pragma", "No-cache");
response.addHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0l);
jedisTemplate.setex(KEY_FORMAT + MAIL_CAPTCHA + customerId, code, Expiration_Time);
// 输出图片
ImageIO.write(verificationCodeImgUtil.getImage(), "JPEG", response.getOutputStream());
System.out.println(code);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}</span></strong>
图片展示效果:
总结:
图片验证码的实现是很简单的,也很实用,一般在注册的时候都会用到.在开发的过程中,遇到过一些问题,解决完以后发现都是小case.
Happy halloween!trick or treat?