ZXing生成二维码

1.什么是二维码?

​ (百度百科):二维码又称二维条码,常见的二维码为QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多的信息,也能表示更多的数据类型。

2.利用ZXING生成二维码

​ ·对应POM

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

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.2.1</version>
</dependency>

​ ·Java代码(生成二维码)

// 二维码的宽度
static final int WIDTH = 300;
// 二维码的高度
static final int HEIGHT = 300;
// 二维码的格式
static final String FORMAT = "png";
// 二维码的内容
static final String TEXT = "Hello!二维码!!!";
/**
 * 生成二维码
 */
 @Test
 public void generate() {
       /*
           定义二维码的参数
        */
       HashMap hashMap = new HashMap();
       // 设置二维码字符编码
       hashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
       // 设置二维码纠错等级
       hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
       // 设置二维码边距
       hashMap.put(EncodeHintType.MARGIN, 2);

       try {
           // 开始生成二维码
           BitMatrix bitMatrix = new MultiFormatWriter().encode(TEXT, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hashMap);
           // 导出到指定目录
           MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, new File("D://erweima.png").toPath());
       } catch (WriterException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

生成出来的二维码!!!

 

​ ·Java代码(读取二维码)

/**
    * 读取二维码
    */
   @Test
   public void read() throws IOException, NotFoundException {
       // 读取二维码为图片
       BufferedImage bufferedImage = ImageIO.read(new File("D://erweima.png"));
       // 获取二维码的结果
       BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
       /*
           定义二维码的参数
        */
       HashMap hashMap = new HashMap();
       // 设置二维码字符编码
       hashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
       // 对图像进行解码
       Result result = new MultiFormatReader().decode(binaryBitmap, hashMap);
       System.out.println("解析二维码的内容是:" + result.getText());
   }

 

 读取二维码里面的内容!!!

 

 

posted @ 2020-01-21 11:22  _running  阅读(6957)  评论(0编辑  收藏  举报