java 生成二维码 QRCode

方案一

借助 hutool 工具

引入依赖

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.16</version>
</dependency>

注意如果生成内容是中文的 使用微信扫码不显示内容,需要复制后自行查询内容,如果内容简单 生成的二维码就简介稀疏,如内容比较多 二维码就比较稠密

    public static void main(String[] args) {
        // 设置二维码的内容
        String content = "生成二维码";
        // 设置二维码的配置
        QrConfig config = new QrConfig(300, 300);
        config.setErrorCorrection(ErrorCorrectionLevel.M); // 设置纠错级别
        // 生成二维码并保存到文件
        QrCodeUtil.generate(content, config, FileUtil.file("E:/qrcode.png"));
        // 或者直接输出到流
        // QrCodeUtil.generate(content, config, System.out);
    }

方案二

引入依赖   借助谷歌组件 google.zxing

注意如果生成内容是中文的 使用微信扫码不显示内容,需要复制后自行查询内容,如果内容简单 生成的二维码就简介稀疏,如内容比较多 二维码就比较稠密

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.4.1</version>
        </dependency>
    @GetMapping("generateQRCode")
    public void generateQRCode(@RequestParam("id") Long id, HttpServletResponse response) {
        try {
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            String content = "生成二维码";
            QRCodeWriter qrCodeWriter = new QRCodeWriter(); 
            BitMatrix bitMatrix = qrCodeWriter.encode( content , BarcodeFormat.QR_CODE, 200, 200, hints);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", byteArrayOutputStream);
            response.setContentType("image/png");
            response.getOutputStream().write(byteArrayOutputStream.toByteArray());
            response.getOutputStream().flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值