生成二维码

 /**
     * 生成二维码
     *
     * @param text 二维码内容
     */
    public static void zxingCodeCreate(String text, String filePath) throws Exception {
        int width = 208; // 图像宽度
        int height = 208; // 图像高度
        String format = "png";//图片格式
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");//字符编码格式
        hints.put(EncodeHintType.MARGIN, 0);//边框宽度
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
                BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {//如果文件夹不存在,创建文件夹
            file.mkdirs();
        }
        if (!file.exists()) {//如果文件不存在,创建文件
            file.createNewFile();
        }
        ImageIO.write(image, format, file);
    }

ImageIO的write方法提供了上面的3种重载形式,第2种方式是将图片写入服务器。1,3种可将图片输出到浏览器端;

相对上面生成二维码图片到本地(或服务器),以下是使用ImageIO生成图片验证码到浏览器的方法

/**
     * 生成验证码
     *
     * @param response
     */
    @RequestMapping("/valicode")
    public void actionValicode(HttpServletResponse response) {
        BufferedImage image = new BufferedImage(90, 30, BufferedImage.TYPE_INT_RGB);
        String valicode = Valicode.drawImage(image);
        String encryptString = BaseUtil.encrypt(valicode.toUpperCase(), BaseUtil.VALICODE_SALT);
        Cookie cookie = new Cookie("vali", encryptString);
        //cookie.setHttpOnly(true);	//增强安全,避免一定程度的跨站攻击,tomcat7
        cookie.setMaxAge(600);
        cookie.setPath("/");
        response.addCookie(cookie);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream output = null;
        try {
            output = response.getOutputStream();
            ImageIO.write(image, "jpeg", output);
            output.flush();
            output.close();
        } catch (IOException e) {

        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值