java 使用zxing生成二维码

简单介绍一下使用google的zxing实现将内容生成为二维码,通过扫码得到。

1.需要用到的依赖如下:

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.0</version>
        </dependency>

2.代码实现:

    /**
     * 
     * @param content    需要生成的内容
     * @param outPath    生成的路径
     * @return
     */
 public static String createCode(String content,String outPath){
        int width = 1200;
        int height = 1200;
        String format = "png";
        System.out.println(content.length());
        // 定义二维码参数
        HashMap hints = new HashMap();
        // 字符集
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 纠错级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 空白
        hints.put(EncodeHintType.MARGIN, 2);
        if(content.length()>1800){
            return null;
        }
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);
            Path file = new File(outPath).toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
            return outPath;
        } catch (Exception e) {
            return null;
        }

    }

 3. 测试:

 public static void main(String[] args) {

        createCode("hello,world!","d:\\H.png");
    }

4.生成效果:

        此处为设定地址path下的二维码,便不贴图了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值