生成图片验证码(数字类型的)接口/工具类
第一步:声明接口
package service.api.system;
import result.Result;
import service.model.base.BaseSystemReqDTO;
import java.io.IOException;
import java.util.Map;
/**
* 开发平台获取图片验证码接口
*
* @author zhangkuankuan
* @version Id: OpenPlatformGetImageService.java, v 0.1 2022-08-12 8:49 zhangkuankuan Exp $$
*/
public interface OpenPlatformGetImageService {
/**
* 获取图片验证码
*/
Result<Map<String, String>> getImageCode(BaseSystemReqDTO reqDTO) throws IOException;
}
第二步:创建工具类
package common.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
/**
* 生成图片验证码工具类
*
* @author zhangkuankuan
* @version Id: VerifyCodeUtils.java.java, v 0.1 2022-08-12 10:15:15 zhangkuankuan Exp $
*/
public class VerifyCodeUtils {
/**
* 使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
*/
public static final String VERIFY_CODES = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static final Random random = new SecureRandom();
/**
* 使用系统默认字符源生成验证码
*
* @param verifySize 验证码长度
* @return String
*/
public static String generateVerifyCode(int verifySize) {
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
*
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return String
*/
public static String generateVerifyCode(int verifySize, String sources) {
if (sources == null || sources.length() == 0) {
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++) {
verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
/**
* 输出指定验证码图片流
*
* @param w w
* @param h h
* @param os os
* @param code code
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,
Color.ORANGE, Color.PINK, Color.YELLOW};
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h - 4);
// 绘制干扰线
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使图片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h - 4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++) {
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1),
(w / verifySize) * i + fontSize / 2, h / 2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
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);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
}
第三步:缓存类
package manager.cache;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* 缓存实现接口
*
* @author liuxulei
* @version Id: CacheService.java, v 0.1 2020/10/10 9:23 AM liuxulei Exp $$
*/
public interface CacheService {
/**
* 缓存数据,永久保存
*
* @param key key
* @param value value
* @return 是否成功
*/
boolean setObject(String key, Object value);
/**
* 缓存数据,有过期时间(自定义)
*
* @param key key
* @param value value
* @param timeout 时间
* @param timeUnit 单位
* @return 是否成功
*/
boolean setObject(final String key, final Object value, final long timeout,
final TimeUnit timeUnit);
/**
* 获取缓存对象
*
* @param key 查询关键字
* @param clazz clazz
* @param <T> t
* @return 是否成功
*/
<T> T get(final String key, final Class<T> clazz);
/**
* 获取缓存对象
*
* @param key 查询关键字
* @return string
*/
String getString(final String key);
/**
* 获取缓存list
*
* @param key key
* @param clazz clazz
* @param <T> t
* @return List<T> list集合
*/
<T> List<T> getList(final String key, final Class<T> clazz);
/**
* 清除缓存
*
* @param key key
* @return boolean
*/
boolean delete(String key);
/**
* 自增并且设置过期时间
*
* @param key key
* @param count count
* @param time time 过期时间毫秒
*/
Long incrementAndUpdateExpireByLua(String key, Long count, Long time);
/**
* 清除缓存
*
* @param key key
* @param count count
*/
void increment(String key, Long count);
/**
* 设置过期时间
*
* @param key key
* @param time time
* @param timeUnit timeUnit
*/
void expire(String key, Long time,TimeUnit timeUnit);
}
package manager.cache.impl;
import common.constant.CacheKeyConstant;
import common.utils.JsonUtils;
import manager.cache.CacheService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* redis缓存操作实现类
*
* @author liuxulei
* @version Id: RedisCacheImpl.java, v 0.1 2020/10/10 9:23 AM liuxulei Exp $$
*/
@Log4j2
@Component
public class RedisCacheImpl implements CacheService {
/**
* 缓存 Key 前缀
*/
public static final String UNITY_CERTIFY = "UNITY_CERTIFY_";
/**
* redis模板
*/
@Autowired
private StringRedisTemplate redisTemplate;
/**
* lua 脚本 项目启动时已初始化
*/
@Autowired
private DefaultRedisScript<Long> redisScript;
/**
* 缓存数据,永久保存
*
* @param key key
* @param value value
* @return 是否成功
*/
@Override
public boolean setObject(String key, Object value) {
return setObject(UNITY_CERTIFY + key, value, 0L, TimeUnit.MILLISECONDS);
}
/**
* 缓存数据,有过期时间(自定义)
*
* @param key key
* @param value value
* @param timeout 时间
* @return boolean
*/
@Override
public boolean setObject(final String key, final Object value, final long timeout,
final TimeUnit timeUnit) {
final String jsonValue = toJson(value);
if (timeout > 0) {
redisTemplate.boundValueOps(UNITY_CERTIFY + key).set(jsonValue, timeout, timeUnit);
} else {
redisTemplate.boundValueOps(UNITY_CERTIFY + key).set(jsonValue);
}
return true;
}
/**
* 获取缓存对象
*
* @param key 查询关键字
* @return <T> T
*/
@Override
public <T> T get(final String key, final Class<T> clazz) {
try {
return JsonUtils.fromJson(redisTemplate.boundValueOps(
UNITY_CERTIFY + key).get(), clazz);
} catch (Exception e) {
log.info("Redis处理异常:{},{}", key, e);
return null;
}
}
/**
* 获取缓存对象
*
* @param key 查询关键字
* @return string
*/
@Override
public String getString(String key) {
try {
return redisTemplate.boundValueOps(
UNITY_CERTIFY + key).get();
} catch (Exception e) {
log.error("Redis处理异常: {}", e);
}
return null;
}
/**
* 获取缓存list
*
* @param key key
* @param clazz class
* @param <T> t
* @return List
*/
@Override
public <T> List<T> getList(final String key, final Class<T> clazz) {
try {
return JsonUtils.jsonToList(redisTemplate.boundValueOps(
UNITY_CERTIFY + key).get(), clazz);
} catch (Exception e) {
log.error("Redis处理异常 error", e);
}
return null;
}
/**
* 清除缓存
*
* @param key key
*/
@Override
public boolean delete(String key) {
redisTemplate.delete(UNITY_CERTIFY + key);
return true;
}
/**
* redis 值如果是对象转成json,如果是字符串不变
*
* @param value 值
* @return 值
*/
private String toJson(Object value) {
if (value instanceof String) {
return (String) value;
}
return JsonUtils.toJson(value);
}
/**
* 清除缓存
*
* @param key key
* @param count count
* @param time time 过期时间 毫秒
*/
@Override
public Long incrementAndUpdateExpireByLua(String key, Long count, Long time) {
try {
// 参数一:redisScript,参数二:key列表,参数三:arg(可多个)
return redisTemplate.execute(redisScript, Collections.singletonList(UNITY_CERTIFY + key),
String.valueOf(time), String.valueOf(count));
} catch (Exception e) {
log.error("Redis自增lua脚本执行异常 error", e);
return -1L;
}
}
/**
* 清除缓存
*
* @param key key
* @param count count
*/
@Override
public void increment(String key, Long count) {
try {
redisTemplate.boundValueOps(UNITY_CERTIFY + key).increment(count);
} catch (Exception e) {
log.error("Redis自增处理异常 error", e);
}
}
/**
* 设置过期时间
*
* @param key key
* @param time time
* @param timeUnit timeUnit
*/
@Override
public void expire(String key, Long time, TimeUnit timeUnit) {
try {
redisTemplate.boundValueOps(UNITY_CERTIFY + key).expire(time, timeUnit);
} catch (Exception e) {
log.error("Redis设置过期时间处理异常 error", e);
}
}
}
第四步:图片验证码接口实现类(生成图片验证码并将value存储到缓存)
package service.system;
import result.Result;
import common.constant.CacheKeyConstant;
import common.utils.VerifyCodeUtils;
import manager.cache.CacheService;
import service.api.system.OpenPlatformGetImageService;
import service.model.base.BaseSystemReqDTO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 开发平台生成图片验证码接口实现类
*
* @author zhangkuankuan
* @version Id: OpenPlatformGetImageServiceImpl.java, v 0.1 2022-08-11 8:49 zhangkuankuan Exp $$
*/
@DubboService
@Component
public class OpenPlatformGetImageServiceImpl implements OpenPlatformGetImageService {
/**
* 图片验证码存放redis
*/
public static final String PICTUER_CAPTCHA = "PICTUER_CAPTCHA";
/**
* 图片验证码存放redis时间
*/
public static final Integer CAPTCHA_EXPIRATION = 5;
/**
* 缓存操作类
*/
@Autowired
private CacheService cacheService;
@Override
public Result<Map<String, String>> getImageCode(BaseSystemReqDTO reqDTO) throws IOException {
//生成随机字串
String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
//唯一标识
String verifyKey = PICTUER_CAPTCHA;
//验证码存入redis
cacheService.setObject(verifyKey, verifyCode, CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
//生成图片
ByteArrayOutputStream stream = new ByteArrayOutputStream();
int wide = 111, high = 36;
VerifyCodeUtils.outputImage(wide, high, stream, verifyCode);
Map<String, String> result = new HashMap<>();
try {
//jdk1.8提供了新的Base64类 可以直接调用
Base64.Encoder encoder = Base64.getEncoder();
result.put("code", "200");
result.put("verifyCode", verifyCode);
result.put("img", encoder.encodeToString(stream.toByteArray()));
result.put("msg", "获取验证码成功");
return new Result<>(result);
} catch (Exception e) {
result.put("code", "500");
result.put("msg", "获取验证码失败,请联系管理人员!");
return new Result<>(result);
} finally {
stream.close();
}
}
}