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

用 Google ZXing 掃描手機相簿中的二維碼圖片

編輯:關於 Android 程式設計

先前做過一個仿微信風格的 ZXing 掃描頁(條碼即時預覽那種),但有時需求不太一樣:使用者手上已經有一張含二維碼的圖片,想直接從相簿挑出來解。本文就在原本的掃描工程上加這個功能。

一、在掃描頁加入入口按鈕

標題列沿用微信的樣式資源,右側放一個 ImageButton 作為「從相簿選圖」的入口,左側保留返回鍵,中間是標題文字。佈局以 RelativeLayout 為底,靠 layout_alignParentRight 把按鈕推到右側即可。

二、開啟相簿並接收結果

點擊監聽中用 ACTION_GET_CONTENT 搭配 image/* 的型別開啟系統相簿,並包一層 Intent.createChooser 讓標題顯示為「選擇二維碼圖片」:

Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
innerIntent.setType("image/*");
Intent wrapperIntent = Intent.createChooser(innerIntent, "選擇二維碼圖片");
this.startActivityForResult(wrapperIntent, REQUEST_CODE);

用 startActivityForResult 而非 startActivity,是因為我們需要拿到使用者選的那張圖。回到 onActivityResult 後,先過濾 requestCode 與 resultCode,再用 ContentResolver 查詢 Uri 對應的實際路徑:

Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
if (cursor.moveToFirst()) {
    photo_path = cursor.getString(
        cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();

拿到路徑後顯示一個不可取消的 ProgressDialog,並在子執行緒中進行解碼,避免解析耗時引發 ANR,結果再透過 Handler 回主執行緒更新 UI:

new Thread(new Runnable() {
    @Override
    public void run() {
        Result result = scanningImage(photo_path);
        Message m = mHandler.obtainMessage();
        m.what = (result != null) ? PARSE_BARCODE_SUC : PARSE_BARCODE_FAIL;
        m.obj = (result != null) ? result.getText() : "Scan failed!";
        mHandler.sendMessage(m);
    }
}).start();

三、解碼方法

ZXing 提供的 QRCodeReader 搭配 decode(BinaryBitmap, Map) 就能完成解析。實作上有兩個細節值得注意:一是設定字元集為 UTF8,否則中文內容容易亂碼;二是先用 inJustDecodeBounds 讀取原圖尺寸做縮放,避免大圖直接進記憶體造成 OOM。

public Result scanningImage(String path) {
    if (TextUtils.isEmpty(path)) return null;

    Hashtable<DecodeHintType, String> hints = new Hashtable<>();
    hints.put(DecodeHintType.CHARACTER_SET, "UTF8");

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    scanBitmap = BitmapFactory.decodeFile(path, options);
    options.inJustDecodeBounds = false;
    int sampleSize = (int) (options.outHeight / (float) 200);
    if (sampleSize <= 0) sampleSize = 1;
    options.inSampleSize = sampleSize;
    scanBitmap = BitmapFactory.decodeFile(path, options);

    RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
    BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
    QRCodeReader reader = new QRCodeReader();
    try {
        return reader.decode(bitmap1, hints);
    } catch (NotFoundException e) {
        e.printStackTrace();
    } catch (ChecksumException e) {
        e.printStackTrace();
    } catch (FormatException e) {
        e.printStackTrace();
    }
    return null;
}

三個例外各有含義:NotFoundException 代表圖中找不到符合的碼,ChecksumException 代表定位到了但資料校驗失敗(通常是影像模糊或反光),FormatException 則是資料結構不合法。UI 上可以據此給出不同提示,使用者體驗會好很多。

四、可以再加強的地方

sampleSize 只看高度,長寬比極端的圖可能仍偏大,實務上取寬高的較小值來算會更穩。另外,解碼完記得回收 Bitmap;若專案已遷到 AndroidX,可考慮 CameraX 搭配 ML Kit 的 barcode scanning,能同時拿到即時預覽與相簿解碼兩種能力,也不必自行維護 ZXing 這份已停止更新的程式碼。

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