ZXing 生成、解析二維碼圖片的小示例


概述

ZXing 是一個開源 Java 類庫用於解析多種格式的 1D/2D 條形碼。目標是能夠對QR編碼、Data Matrix、UPC的1D條形碼進行解碼。 其提供了多種平台下的客戶端包括:J2ME、J2SE和Android。

官網:ZXing github倉庫

實戰

本例演示如何在一個非 android 的 Java 項目中使用 ZXing 來生成、解析二維碼圖片。

安裝

maven項目只需引入依賴:

<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>

如果非maven項目,就去官網下載發布版本:下載地址

生成二維碼圖片

ZXing 生成二維碼圖片有以下步驟:

  1. com.google.zxing.MultiFormatWriter 根據內容以及圖像編碼參數生成圖像2D矩陣。
  2. com.google.zxing.client.j2se.MatrixToImageWriter 根據圖像矩陣生成圖片文件或圖片緩存 BufferedImage
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);
}

解析二維碼圖片

ZXing 解析二維碼圖片有以下步驟:

  1. 使用 javax.imageio.ImageIO 讀取圖片文件,並存為一個 java.awt.image.BufferedImage 對象。

  2. java.awt.image.BufferedImage 轉換為 ZXing 能識別的 com.google.zxing.BinaryBitmap 對象。

  3. com.google.zxing.MultiFormatReader 根據圖像解碼參數來解析 com.google.zxing.BinaryBitmap

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();
}

完整參考示例:測試例代碼

以下是一個生成的二維碼圖片示例:

qrcode.png

參考

ZXing github倉庫


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM