基本参数
/**
* 随机验证码生成访问
*/
private static final String RANGE_RANDOM_STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* 图片尺寸设置
*/
private static final int WIDTH = 100;
private static final int HEIGHT = 32;
/**
* 干扰线段数量
*/
private static final int LINE_NUM = 40;
/**
* 随机验证码个数
*/
private static final int STE_NUM = 4;
/**
* 验证码默认字体
*/
private static final Font DEFAULT_FONT = new Font("Times New Roman", Font.ROMAN_BASELINE, 22);
/**
* 随机数工具
*/
private static final Random RANDOM = new Random();
获取随机字符串
public static String getRandomString() {
StringBuffer rssb = new StringBuffer();
for(int index = 0; index < STE_NUM; index++) {
rssb.append(RANGE_RANDOM_STR.charAt(RANDOM.nextInt(RANGE_RANDOM_STR.length())));
}
return rssb.toString();
}
获得随机颜色
private static Color getRandColor(int fc, int bc) {
if (fc > 255) fc = 255;
if (bc > 255) bc = 255;
int r = fc + RANDOM.nextInt(bc - fc - 16);
int g = fc + RANDOM.nextInt(bc - fc - 14);
int b = fc + RANDOM.nextInt(bc - fc - 18);
return new Color(r, g, b);
}
绘制干扰线
private static void drowLine(Graphics graphics) {
int x = RANDOM.nextInt(WIDTH);
int y = RANDOM.nextInt(HEIGHT);
int xl = RANDOM.nextInt(13);
int yl = RANDOM.nextInt(15);
graphics.drawLine(x, y, x + xl, y + yl);
}
绘制字符串
private static void drowString(Graphics graphics, String randomString) {
// 设置字体样式
graphics.setFont(DEFAULT_FONT);
// 设置字体颜色
graphics.setColor(new Color(RANDOM.nextInt(101), RANDOM.nextInt(111), RANDOM.nextInt(121)));
graphics.translate(RANDOM.nextInt(3), RANDOM.nextInt(3));
graphics.drawString(randomString, 20, 20);
}
获取图片
/**
* 获取图片验证码。
*/
public static BufferedImage getImage(String randomString) {
// 创建绘图对象
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR);
Graphics graphics = image.getGraphics();
// 绘图大小
graphics.fillRect(0, 0, WIDTH, HEIGHT);
// 字体大小
graphics.setFont(DEFAULT_FONT);
// 字体颜色
graphics.setColor(getRandColor(110, 133));
// 绘制干扰线
for (int i = 0; i <= LINE_NUM; i++) {
drowLine(graphics);
}
// 绘制随机字符串
drowString(graphics, randomString);
graphics.dispose();
return image;
}
/**
* 获取图片验证码。
*/
public static BufferedImage getImage() {
return getImage(getRandomString());
}
HTTP响应设置
// 设置相应类型。输出的内容为图片
response.setContentType("image/jpeg");
// 设置响应头信息。不要缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
try {
// 根据随机字符串,生成图片对象
String randomString = VerifyUtils.getRandomString();
BufferedImage image = VerifyUtils.getImage(randomString);
// 将内存中的图片通过流动形式输出到客户端
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (IOException e) {
LOGGER.error("IOException : {}", e.getMessage(), e);
}