java中ZXing 生成、解析二維碼圖片的小示例
概述
ZXing 是一個開源 Java 類庫用于解析多種格式的 1D/2D 條形碼。目標是能夠?qū)R編碼、Data Matrix、UPC的1D條形碼進行解碼。 其提供了多種平臺下的客戶端包括:J2ME、J2SE和Android。
官網(wǎng):ZXing github倉庫
實戰(zhàn)
本例演示如何在一個非 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項目,就去官網(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 讀取圖片文件,并存為一個 java.awt.image.BufferedImage 對象。
2.將 java.awt.image.BufferedImage 轉(zhuǎn)換為 ZXing 能識別的 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(); }
完整參考示例:測試例代碼
以下是一個生成的二維碼圖片示例:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SSH框架網(wǎng)上商城項目第15戰(zhàn)之線程、定時器同步首頁數(shù)據(jù)
這篇文章主要為大家詳細介紹了SSH框架網(wǎng)上商城項目第15戰(zhàn)之線程、定時器同步首頁數(shù)據(jù),感興趣的小伙伴們可以參考一下2016-06-06Java中從Integer到Date的轉(zhuǎn)換方法
這篇文章主要介紹了Java中integer怎么轉(zhuǎn)換date,在Java中,如果我們有一個Integer類型的數(shù)據(jù),想要將其轉(zhuǎn)換為Date類型,本文給大家介紹了實現(xiàn)方法,并通過代碼示例講解的非常詳細,需要的朋友可以參考下2024-05-05