使用zxing生成二维码

pom配置

    <dependency>  
        <groupId>com.google.zxing</groupId>  
        <artifactId>core</artifactId> 
        <version>3.0.0</version>
    </dependency>  
    <dependency>    
        <groupId>com.google.zxing</groupId>    
        <artifactId>javase</artifactId>    
        <version>3.0.0</version>  
    </dependency>  
    <dependency>    
          <groupId>com.alibaba</groupId>    
          <artifactId>fastjson</artifactId>    
          <version>1.1.29</version>  
    </dependency>

生成一串包含json数据的二维码

  • 此方法会生成一个二维码, 手机扫描后得到一串json数据
      public class QRCodeTest {
      public static void main(String[] args) throws WriterException, IOException {
          String filePath = "D://";
          String fileName = "zxing.png";
          JSONObject json = new JSONObject();
          json.put("zxing", "https://www.baidu.com");
          json.put("author", "yangzhongyang");
          String content = json.toJSONString(); //内容
          int width = 200; //图像宽度
          int height = 200; //图像高度
          String format = "png"; //图像类型
          Map<EncodeHintType, Object> hints = new HashMap<>();
          hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
          BitMatrix bitMatrix = new MultiFormatWriter()
                  .encode(content, BarcodeFormat.QR_CODE, width, height, hints);
          Path path = FileSystems.getDefault().getPath(filePath, fileName);
          MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
        }
    }

生成一个带Url连接的二维码

  • 此方法生成二维码包含一个Url地址连接, 使用手机扫描后会自动跳转到指定的Url地址
    public static void main(String[] args) throws WriterException, IOException {
            String filePath = "D://";
            String fileName = "zxing.png";
            
            int width = 200; //图像宽度
            int height = 200; //图像高度
            String format = "png"; //图像类型
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter()
                    .encode("http://www.huiedu.com.cn", BarcodeFormat.QR_CODE, width, height, hints);
            Path path = FileSystems.getDefault().getPath(filePath, fileName);
            MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容