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

Android 二維碼實戰:用 ZXing 完成生成、掃描與長按識別

編輯:關於 Android 程式設計

先把 ZXing 掛進專案

二維碼在現在的 App 裡幾乎是標配,但從零打造掃碼引擎成本太高,也沒必要。GitHub 上最有名的方案就是 ZXing,它橫跨多個平台,開源地址為 https://github.com/zxing/zxing。

第一步,下載核心 jar:
https://repo1.maven.org/maven2/com/google/zxing/core/3.2.1/ ,取 core-3.2.1.jar 即可。早期版本把 jar 丟進專案常跑不起來,只能導入原始碼,現在已經沒這個問題。另外還需要 android-core-3.2.1.jar,或者把裡面那唯一一個類複製進專案也可以。

第二步,從開源頁下載完整專案(一百多 MB),把 android 子專案裡的 src 原始碼與資源檔複製到自己的工程。接著以 Android Studio 為例:

複製完成後要處理三件事:AndroidManifest 中的 Activity 宣告都寫的是相對類名,換了包名就得逐一修正;接著處理 R 檔案的引用錯誤;最後 BookmarkPickerActivity 大約第 50 行會在 Browser.BOOKMARKS_URI 上報錯,把 compileSdkVersion 改成 22 就能解決。

到這一步應該就能跑起來掃碼了。

只留核心功能

ZXing 本體功能繁多、體積龐大,實務上我們只需要抽出掃碼與解碼那一小块。網路上已有不少人是照著最早那位前輩的抽取版本改的,而那個版本基於 ZXing 1.5/2.3,類別寫法偏舊。比較省事的做法是拿舊的抽取結果,把裡面的類逐步替換成新版 ZXing 的實作。

這裡提供一個基於 ZXing 3.1 封裝的版本,含最新 jar 與程式碼,已經把橫豎屏、扭曲變形等常見問題處理過,並附上編碼/解碼方法,掃碼畫面也抽成了 XML,方便替換擴充。

生成二維碼

呼叫方式很簡單,兩個參數分別是內容與正方形邊長(px):

Bitmap bitmap = null;
try {
    bitmap = BitmapUtil.createQRCode(msg, 400);
} catch (WriterException e) {
    e.printStackTrace();
}
imageView.setImageBitmap(bitmap);

接著把 bitmap 設到目標 ImageView 上就完成了。

長按識別:截屏 + 解析

微信那種長按辨識二維碼,思路其實很直白:既然掃碼能解,那相機擷取到的圖也能解。所以長按時只要對當前畫面截圖,再把圖檔丟給解析方法即可。

// 這種寫法狀態欄會是空白,看不到狀態欄資訊
private void saveCurrentImage() {
    int width = getWindow().getDecorView().getRootView().getWidth();
    int height = getWindow().getDecorView().getRootView().getHeight();
    Bitmap temBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
    View view = getWindow().getDecorView().getRootView();
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    temBitmap = view.getDrawingCache();
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    time = df.format(new Date());
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/screen", time + ".png");
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); }
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            temBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) { e.printStackTrace(); }
        catch (IOException e) { e.printStackTrace(); }
    }
}

圖存下來之後,把路徑傳給解析方法即可:

// 解析二維碼圖片,結果封裝在 Result 物件中
private com.google.zxing.Result parseQRcodeBitmap(String bitmapPath) {
    Hashtable<DecodeHintType, String> hints = new Hashtable<>();
    hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

    BitmapFactory.Options options = new BitmapFactory.Options();
    // 先只取寬高,不真的解出 Bitmap
    options.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath, options);

    // 二維碼是正方形,這裡把邊長控制在 400px
    options.inSampleSize = options.outHeight / 400;
    if (options.inSampleSize <= 0) options.inSampleSize = 1;
    options.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFile(bitmapPath, options);

    RGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource(bitmap);
    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(rgbLuminanceSource));
    QRCodeReader reader = new QRCodeReader();
    Result result = null;
    try {
        result = reader.decode(binaryBitmap, hints);
    } catch (Exception e) {
        // 解析失敗就走這裡
    }
    return result;
}

還缺一個 RGBLuminanceSource

依 ZXing 的解碼流程,我們只需要自己實作一個 LuminanceSource 子類。它繼承自抽象類 LuminanceSource,要實作構造方法(傳入圖片寬高)、getMatrix() 與 getRow(int y, byte[] row)。getMatrix() 回傳的是整張圖的像素陣列;getRow() 顧名思義,取出第 y 行的像素資料。

public class RGBLuminanceSource extends LuminanceSource {
    private byte bitmapPixels[];

    protected RGBLuminanceSource(Bitmap bitmap) {
        super(bitmap.getWidth(), bitmap.getHeight());
        int[] data = new int[bitmap.getWidth() * bitmap.getHeight()];
        this.bitmapPixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
        bitmap.getPixels(data, 0, getWidth(), 0, 0, getWidth(), getHeight());
        // int 轉 byte,實際上只取每個像素的藍色分量
        for (int i = 0; i < data.length; i++) {
            this.bitmapPixels[i] = (byte) data[i];
        }
    }

    @Override
    public byte[] getMatrix() {
        return bitmapPixels;
    }

    @Override
    public byte[] getRow(int y, byte[] row) {
        System.arraycopy(bitmapPixels, y * getWidth(), row, 0, getWidth());
        return row;
    }
}

這裡要特別說明:上面取得的 byte[] 是圖片的像素陣列,不是「把 Bitmap 序列化成 byte[]」。Bitmap.getPixels() 回傳的是 int 陣列,每個值代表一個像素的顏色(含 alpha 與 RGB),白色是 0xffffffff、黑色是 0xff000000。直接從 int 轉 byte,效果等同只取藍色分量。

getPixels() 拿到的是一維陣列,依寬度逐行填寫。想取單行,用 y × width 定位到該行起點,再複製 width 個即可。

最後記得一件事:解析要放在子執行緒裡做,否則容易 ANR。把長按存下的圖檔路徑傳進 parseQRcodeBitmap(),生成、讀取、識別這條鏈路就完整了。

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