簡介
ZXing 是一個(gè)開源 JAVA 類庫用于解析多種格式的 1D/2D 條形碼。目標(biāo)是能夠?qū)R編碼、Data Matrix、UPC的1D條形碼進(jìn)行解碼。其提供了多種平臺(tái)下的客戶端包括:J2ME、J2SE和Android。
官網(wǎng):ZXing github倉庫
實(shí)戰(zhàn)
本例演示如何在一個(gè)非 android 的 Java 項(xiàng)目中使用 ZXing 來生成、解析二維碼圖片。
安裝
maven項(xiàng)目只需引入依賴:
<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項(xiàng)目,就去官網(wǎng)下載發(fā)布版本:下載地址
生成二維碼圖片
ZXing 生成二維碼圖片有以下步驟:
1.com.google.zxing.MultiFormatWriter 根據(jù)內(nèi)容以及圖像編碼參數(shù)生成圖像2D矩陣。
2.com.google.zxing.client.j2se.MatrixToImageWriter 根據(jù)圖像矩陣生成圖片文件或圖片緩存 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 讀取圖片文件,并存為一個(gè)
java.awt.image.BufferedImage對象。
2.將
java.awt.image.BufferedImage 轉(zhuǎn)換為 ZXing 能識(shí)別的com.google.zxing.BinaryBitmap 對象。
3.com.google.zxing.MultiFormatReader 根據(jù)圖像解碼參數(shù)來解析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();
}