java 生成图片验证码

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 图片验证码工具类
 * @author fzg
 */
@Slf4j
@Service
public class ImageCodeTool {
    /**
     * 图片验证码缓存器
     */
    public static TimedCache<String, String> imageCodeCache = CacheUtil.newTimedCache(6000000);

    /**
     * 获得图片验证码
     * @return imageCodeKey、imageCodeBase64
     */
    public static Map<String, Object> getImageCode() {
        //启动定时器,没1秒清理一次
        imageCodeCache.schedulePrune(10000000);

        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        //将数据存储到缓存器中
        String imageCodeKey = IdUtil.simpleUUID();
        String imageCodeBase64 = circleCaptcha.getImageBase64Data();
        imageCodeCache.put(imageCodeKey, circleCaptcha.getCode());
        //返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("imageCodeKey", imageCodeKey);

        result.put("imageCodeBase64", imageCodeBase64);
        log.info(circleCaptcha.getCode());
        return result;
    }

    /**
     * 校验图片验证码
     * @param imageCodeKey 验证码秘钥
     * @param imageCode 验证码
     * @return
     */
    public static boolean imageCodeCheck(String imageCodeKey, String imageCode) {
        String code = imageCodeCache.get(imageCodeKey);
        if(code == null) {
            return false;
        }
        else {
            if(code.equals(imageCode)) {
                return true;
            }else {
                return false;
            }
        }
    }
}
posted @ 2022-11-30 10:15  合起来的彳亍  阅读(30)  评论(0编辑  收藏  举报