当前位置: 首页 > 工具软件 > XVcode > 使用案例 >

XVcode图形验证码生成

宋斌
2023-12-01

生成并保存到本地

//生成验证码图片到本地磁盘 draw image and save to disk
    public String PicCode() {
        String path = ".";//图片存储路径 path for image save
        Integer height = 40;//image 高度。  image height. count as pixel
        Integer width = 160;//image 宽度。 image width. count as pixel
        Integer count = 6;  // validation code length.
        String validCode = null; //验证码
        Generator generator = new PngVCGenerator(width, height, count);
        try {
            generator.write2out(new FileOutputStream(path + "/codepic.png")).close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        validCode = generator.text(); //get the validation code as 'String'

//      保存字符串
        stringRedisTemplate.opsForValue().set("code", validCode);
        return stringRedisTemplate.opsForValue().get("code");
//        return validCode;
    }

生成并保存到数据流

public String setCaptchaCodeInCache(HttpServletResponse response) throws UnsupportedEncodingException {
        Integer height = 40;//image 高度。  image height. count as pixel
        Integer width = 160;//image 宽度。 image width. count as pixel
        Integer count = 6;  // validation code length.
        PngVCGenerator generator = new PngVCGenerator(width, height, count);

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");

        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try {
            sos = response.getOutputStream();
            generator.write2out(sos);
            String validCode = generator.text(); //get the validation code as 'String'
            byte[] toEncode = generator.toString().getBytes("utf-8");
            String asB64 = Base64.getEncoder().encodeToString(toEncode);
            sos.close();
            stringRedisTemplate.opsForValue().set("code", validCode);
            return asB64;
        } catch (IOException e) {
            return "write captcha img error";
        }
    }
 类似资料: