Base64生成验证码

Base64生成验证码

通过工具类生成key和图片验证码
public class VerifyUtil {
    // 验证码字符集
    private static final char[] chars = {
            '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n',
            'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
    // 字符数量
    private static final int SIZE = 4;
    // 干扰线数量
    private static final int LINES = 4;
    // 宽度
    private static final int WIDTH = 83;
    // 高度
    private static final int HEIGHT = 40;
    // 字体大小
    private static final int FONT_SIZE = 30;

    private static int[] w = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};

    /**
     * 生成随机验证码及图片
     * Object[0]:验证码字符串;
     * Object[1]:验证码图片。
     */
    public static Object[] createImage() {
        StringBuffer sb = new StringBuffer();
        // 1.创建空白图片
        BufferedImage image = new BufferedImage(
                WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        // 2.获取图片画笔
        Graphics graphic = image.getGraphics();
        // 3.设置画笔颜色
        graphic.setColor(Color.LIGHT_GRAY);
        // 4.绘制矩形背景
        graphic.fillRect(0, 0, WIDTH, HEIGHT);
        // 5.画随机字符
        Random ran = new Random();
        for (int i = 0; i <SIZE; i++) {
            // 取随机字符索引
            int n = ran.nextInt(chars.length);
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 设置字体大小
            graphic.setFont(new Font(
                    null, Font.BOLD + Font.ITALIC, FONT_SIZE));
            // 画字符
            graphic.drawString(
                    chars[n] + "", i * WIDTH / SIZE, HEIGHT*2/3);
            // 记录字符
            sb.append(chars[n]);
        }
        // 6.画干扰线
        for (int i = 0; i < LINES; i++) {
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 随机画线
            graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
                    ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
        }
        // 7.返回验证码和图片
        return new Object[]{sb.toString(), image};
    }

    /**
     * 随机取色
     */
    public static Color getRandomColor() {
        Random ran = new Random();
        Color color = new Color(ran.nextInt(256),
                ran.nextInt(256), ran.nextInt(256));
        return color;
    }
}
对图片验证码进行Base64编码
@RequestMapping("/face/getverifycode")
@ResponseBody
public Object getVerifyCode() {
        RequestResult requestResult = new RequestResult();
        requestResult.setCode(ResultTypeEnum.FU_SUCCESS_0000.getCode());
        requestResult.setMessage(ResultTypeEnum.FU_SUCCESS_0000.getDesc());

        Map dataMap = new HashMap(4);

        ByteArrayOutputStream outputStream = null;
        try {
            Object[] objects = VerifyUtil.createImage();
            // 得到图片
            BufferedImage image = (BufferedImage) objects[1];
            // 得到验证码
            String valueCode = objects[0].toString().toLowerCase();
            // 生成redis的key
            String key = UUID.randomUUID().toString();
            // 放入redis缓存,时间设置为1分钟
            redisUtil.set(key, valueCode, 1, TimeUnit.MINUTES);
            // 生成base64字符串
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", outputStream);
            // base64将输出流程的byte[] 进行转码
            String pic = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            dataMap.put("codekey", key);
            dataMap.put("codepic", pic);

            requestResult.setData(dataMap);
        } catch (Exception e) {
            log.error("生成验证码错误", e);
            requestResult.setCode(ResultTypeEnum.FU_EXC_9702.getCode());
            requestResult.setMessage(ResultTypeEnum.FU_EXC_9702.getDesc());
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException ex) {
                log.error("关闭流错误", ex);
            }
        }
        return requestResult;
    }
前端页面调用方法
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-type" content="text/html;charset=utf-8">
    <meta name="viewport"
          content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,initial-scale=1.0,user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no">
    <meta name="format-detection" content="email=no">
    <title></title>
    // 这个地方我使用的是thymeleaf,所以引入资源文件不一样,各位可以根据实际情况进行替换
    <link rel="stylesheet" th:href="@{/css/common.css}"/>
    <script type="text/javascript" th:src="@{/js/jquery-2.1.4.min.js}"></script>
    <script th:inline="javascript">
        $(function(){
            refreshimg();
        });

        function refreshimg () {
            $.ajax({
                type : "post",
                dataType : "json",
                url : "/face/getverifycode",
                data : {},
                success : function(data){
                    if (data.data) {
                        $('#randomImage').attr('src', 'data:image/png;base64,'+ data.data.codepic);
                        $("#codekey").val(data.data.codekey);
                    }
                },
                error : function(){
                    console.log("生成验证码错误!");
                }
            });
        }
    </script>
    <style>
        .inputCodeClass {
            flex: 1;
            height: 1.6rem;
            line-height: 1.6rem;
            font-size: 1.4rem;
            width: 6rem;
            text-align: right;
            margin: 0 0.4rem;
            color: red;
            border: none;
            outline: none;
            font-weight: bold;
        }
    </style>
</head>

<body>
<section class="withdrawResult">
    <article class="protocol_content">
        <div style="padding-top: 20px;display: flex;">
            <p>
                <span>验证码:</span>
                <input class="inputCodeClass" type="text" id="inputCode" name="inputCode" style="text-align: left;border: 1px solid #686868"/>
                <input type="hidden" id="codekey" name="codekey" value=""/>
            </p>
            <img id="randomImage" title="点击更换" onclick="javascript:refreshimg()" src=""/>
        </div>
    </article>
</section>
</body>
</html>
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值