当前位置 博文首页 > BestTomDoG的博客:JAVA生成图形验证码并返回给前台,SpringBoot+

    BestTomDoG的博客:JAVA生成图形验证码并返回给前台,SpringBoot+

    作者:[db:作者] 时间:2021-07-04 12:58

    JAVA生成图形验证码并返回给前台,SpringBoot+vue
    @GetMapping("/createCaptchaImage")
    public ResultModel getCode(HttpServletResponse response) throws IOException
    {
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
    
        redisCache.setCacheObject(verifyKey, verifyCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try
        {
            ResultModel ajax = ResultModel.success();
            ajax.put("uuid", uuid);
            ajax.put("img", Base64.encode(stream.toByteArray()));
            return ajax;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return ResultModel.error(e.getMessage());
        }
        finally
        {
            stream.close();
        }
    }
    cs