首頁 > Java > java教程 > 主體

java中ZXing 產生、解析二維碼圖片的小範例

高洛峰
發布: 2017-01-20 14:16:19
原創
1633 人瀏覽過

概述

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

實戰

本例示範如何在一個非 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>
登入後複製

產生二維碼圖片

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

1.com.產生影像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.BufferedImmage。

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();
}
登入後複製

   

以下是一個產生的二維碼圖片範例:

java中ZXing 生成、解析二维码图片的小示例

以上就是本文的全部內容,希望對大家學習多幫助,也希望多多支持PH網。

更多java中ZXing 產生、解析二維碼圖片的小範例相關文章請關注PHP中文網!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!