使用zxing生成二维码

2016-12-12  本文已影响0人  Akademos

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数据的二维码

      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连接的二维码

    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);// 输出图像
    }
上一篇 下一篇

猜你喜欢

热点阅读