ZXing创建和读取二维码示例

文章来源于 ZXing 生成、解析二维码图片的小示例

引入依赖

1
2
3
4
5
6
7
8
9
10
<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.3.0</version>
</dependency>

生成二维码图片

  • com.google.zxing.MultiFormatWriter生成矩阵BitMatrix
  • com.google.zxing.client.j2se.MatrixToImageWriterBitMatrix变成文件或者字节流
1
2
3
4
5
6
7
8
9
public void encode(String content, String filepath) throws WriterException, IOException {
int width = 100;
int height = 100;
Map<EncodeHintType, Object> encodeHints = new HashMap<EncodeHintType, Object>();
encodeHints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, encodeHints);
Path path = FileSystems.getDefault().getPath(filepath);
MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
}

解析二维码图片

  • ImageIO把文件或者流生成BufferedImage
  • BufferedImage->com.google.zxing.BinaryBitmap
  • com.google.zxing.MultiFormatReader 根据参数来解析 om.google.zxing.BinaryBitmap
1
2
3
4
5
6
7
8
9
10
public String decode(String filepath) throws IOException, NotFoundException {
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, decodeHints);
return result.getText();
}

参考