Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實作 QR Code 產生與解析的完整流程

編輯:關於 Android 程式設計

本文示範如何在 Android 上產生並解析 QR Code,程式碼中附有逐行說明,並提供所需的 jar 檔供下載:二維碼Jar包.rar。

一、依文字內容產生 QR Code

核心是 ZXing 的 QRCodeWriter:先把文字編碼成 BitMatrix,再逐像素轉成 Bitmap 顯示出來。這裡指定 CHARACTER_SET 為 utf-8,避免中文出現亂碼。

 // 生成QR圖 private void createImage() { try { // 需要引入core包 QRCodeWriter writer = new QRCodeWriter(); String text = qr_text.getText().toString(); Log.i(TAG, "生成的文本:" + text); if (text == null || "".equals(text) || text.length() < 1) { return; } // 把輸入的文本轉為二維碼 BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT); System.out.println("w:" + martix.getWidth() + "h:" + martix.getHeight()); Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints); int[] pixels = new int[QR_WIDTH * QR_HEIGHT]; for (int y = 0; y < QR_HEIGHT; y++) { for (int x = 0; x < QR_WIDTH; x++) { if (bitMatrix.get(x, y)) { pixels[y * QR_WIDTH + x] = 0xff000000; } else { pixels[y * QR_WIDTH + x] = 0xffffffff; } } } Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT); qr_image.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } } 

幾個實作細節值得留意:QR_WIDTH 與 QR_HEIGHT 建議直接對應輸出圖 desired 尺寸,因為 QR Code 是方形且放大後不失真;先在 hints 中指定編碼為 utf-8 再編碼,能避免中文被錯誤解讀;最後用 setPixels() 一次性寫入像素陣列,比逐點 setPixel() 快得多。

二、從 QR Code 圖片還原內容

解析端流程是:取得 Bitmap → 轉成 RGBLuminanceSource → 用 HybridBinarizer 做二值化 → 交給 QRCodeReader 解碼。

 // 解析QR圖片 private void scanningImage() { Map<DecodeHintType, String> hints = new HashMap<DecodeHintType, String>(); hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 獲得待解析的圖片 Bitmap bitmap = ((BitmapDrawable) qr_image.getDrawable()).getBitmap(); RGBLuminanceSource source = new RGBLuminanceSource(bitmap); BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source)); QRCodeReader reader = new QRCodeReader(); Result result; try { result = reader.decode(bitmap1, hints); // 得到解析後的文字 qr_result.setText(result.getText()); } catch (NotFoundException e) { e.printStackTrace(); } catch (ChecksumException e) { e.printStackTrace(); } catch (FormatException e) { e.printStackTrace(); } } 

這裡的 HybridBinarizer 比預設的 GlobalHistogramBinarizer 更能應付光線不均勻的照片,實務上辨識率明顯更高。三個例外各有含義:NotFoundException 代表圖中找不到 QR Code 圖案,ChecksumException 代表解出的資料校驗失敗(通常是圖片模糊),FormatException 則代表資料格式不符 QR 規格。

以上就是 Android 上 QR Code 產生與解析的完整做法,希望對你的開發有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved