Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 使用 Google ZXing 解析手機相簿裡的二維碼圖片

編輯:Android 開發實例

先前我寫過一篇用 Google ZXing 做即時掃描的文章,成品刻意模仿微信那套交互體驗,有興趣的讀者可以對照著看。不過實務上經常碰到另一種情境:要讀的二維碼並不在眼前,而是早已躺在手機相簿中的一張圖片。這時候要做的就不是即時取像,而是把既有檔案解開來。

需求拆解

整體流程其實只有三段:先讓使用者從相簿挑一張圖,接著取得該圖的真實路徑,最後交給 ZXing 解碼。我這次是直接在原本的掃描工程上擴充,沒有另開新專案,並在掃描頁面的標題列右側補上一個 ImageButton 作為相簿入口,圖示沿用微信素材。

一、標題列加入相簿入口

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="fill_parent" 
  4.     android:layout_height="wrap_content" 
  5.     android:background="@drawable/mmtitle_bg_alpha" > 
  6.  
  7.     <Button 
  8.         android:id="@+id/button_back" 
  9.         android:layout_width="75.0dip" 
  10.         android:layout_height="wrap_content" 
  11.         android:layout_alignParentLeft="true" 
  12.         android:background="@drawable/mm_title_back_btn" 
  13.         android:text="返回" 
  14.         android:textColor="@android:color/white" /> 
  15.  
  16.     <TextView 
  17.         android:id="@+id/textview_title" 
  18.         android:layout_width="wrap_content" 
  19.         android:layout_height="wrap_content" 
  20.         android:layout_centerHorizontal="true" 
  21.         android:layout_centerVertical="true" 
  22.         android:gravity="center_vertical" 
  23.         android:text="二維碼掃描" 
  24.         android:textColor="@android:color/white" 
  25.         android:textSize="18sp" /> 
  26.  
  27.     <ImageButton 
  28.         android:id="@+id/button_function" 
  29.         android:layout_width="wrap_content" 
  30.         android:layout_height="wrap_content" 
  31.         android:layout_alignParentRight="true" 
  32.         android:layout_marginRight="2dip" 
  33.         android:background="@drawable/mm_title_right_btn" 
  34.         android:minWidth="70dip" 
  35.         android:src="@drawable/mm_title_btn_menu_normal" /> 
  36.  
  37. </RelativeLayout> 

二、用 ACTION_GET_CONTENT 開啟相簿

在 MipcaActivityCapture 中掛上點擊監聽,按下按鈕後以系統的內容選擇器開啟相簿。這裡用 Intent.ACTION_GET_CONTENT 搭配 image/* 的型別,讓系統把所有可能的來源(相簿、檔案總管、雲端硬碟等)都列出來:

  1. //打開手機中的相冊  
  2.             Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); //"android.intent.action.GET_CONTENT"  
  3.             innerIntent.setType("image/*");  
  4.             Intent wrapperIntent = Intent.createChooser(innerIntent, "選擇二維碼圖片");  
  5.             this.startActivityForResult(wrapperIntent, REQUEST_CODE); 

三、在 onActivityResult 中完成解碼

因為用的是 startActivityForResult,使用者選好圖片後會回到 onActivityResult 這個回呼點。 here 我們先用 ContentResolver 把 Uri 換算成實際檔案路徑,再開一條子執行緒去解碼——圖片解碼與二維碼運算都頗耗時,放在主執行緒很容易觸發 ANR,所以一定要搬出去,結果再用 Handler 回丟給 UI:

  1. @Override 
  2.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  3.         super.onActivityResult(requestCode, resultCode, data);  
  4.         if(resultCode == RESULT_OK){  
  5.             switch(requestCode){  
  6.             case REQUEST_CODE:  
  7.                 //獲取選中圖片的路徑  
  8.                 Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);  
  9.                 if (cursor.moveToFirst()) {  
  10.                     photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));  
  11.                 }  
  12.                 cursor.close();  
  13.                   
  14.                 mProgress = new ProgressDialog(MipcaActivityCapture.this);  
  15.                 mProgress.setMessage("正在掃描...");  
  16.                 mProgress.setCancelable(false);  
  17.                 mProgress.show();  
  18.                   
  19.                 new Thread(new Runnable() {  
  20.                     @Override 
  21.                     public void run() {  
  22.                         Result result = scanningImage(photo_path);  
  23.                         if (result != null) {  
  24.                             Message m = mHandler.obtainMessage();  
  25.                          m.what = PARSE_BARCODE_SUC;  
  26.                          m.obj = result.getText();  
  27.                          mHandler.sendMessage(m);  
  28.                         } else {  
  29.                          Message m = mHandler.obtainMessage();  
  30.                          m.what = PARSE_BARCODE_FAIL;  
  31.                          m.obj = "Scan failed!";  
  32.                          mHandler.sendMessage(m);  
  33.                         } 
  34.                     }  
  35.                 }).start();  
  36.                  
  37.                break;  
  38.               
  39.             }  
  40.         }  
  41.     } 

四、scanningImage:真正的解碼工作

ZXing 的 QRCodeReader 提供了 decode(BinaryBitmap image, Map<DecodeHintType, ?> hints),只要把圖片包成 BinaryBitmap 就能拿到結果。這裡有兩個值得留意的細節:

第一是編碼問題。二維碼內容如果是中文,預設解出來常常是亂碼,所以我們透過 hint 明確指定 UTF-8。第二是記憶體問題。手機相片的解析度動輒數千像素,直接 decode 進記憶體很容易 OOM;實務上的做法是先用 inJustDecodeBounds = true 只讀取尺寸資訊,據此算出 inSampleSize 做降採樣,把圖片壓縮到 200 像素上下再真正解碼。二維碼的定位標記在這個尺寸下仍然清晰可辨,運算量卻大幅下降。

  1. /**  
  2.  * 掃描二維碼圖片的方法  
  3.  * @param path  
  4.  * @return  
  5.  */ 
  6. public Result scanningImage(String path) {  
  7.     if(TextUtils.isEmpty(path)){  
  8.         return null;  
  9.     }  
  10.     Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();  
  11.     hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); 
  12.  
  13.     BitmapFactory.Options options = new BitmapFactory.Options();  
  14.     options.inJustDecodeBounds = true; // 先獲取原大小  
  15.     scanBitmap = BitmapFactory.decodeFile(path, options);  
  16.     options.inJustDecodeBounds = false; // 獲取新的大小  
  17.     int sampleSize = (int) (options.outHeight / (float) 200);  
  18.     if (sampleSize <= 0) 
  19.         sampleSize = 1;  
  20.     options.inSampleSize = sampleSize;  
  21.     scanBitmap = BitmapFactory.decodeFile(path, options);  
  22.     RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);  
  23.     BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));  
  24.     QRCodeReader reader = new QRCodeReader();  
  25.     try {  
  26.         return reader.decode(bitmap1, hints);  
  27.     } catch (NotFoundException e) {  
  28.         e.printStackTrace();  
  29.     } catch (ChecksumException e) {  
  30.         e.printStackTrace();  
  31.     } catch (FormatException e) {  
  32.         e.printStackTrace();  
  33.     } 
  34.     return null;  
  35. } 

三個例外各自代表不同的失敗原因:NotFoundException 是畫面裡找不到任何碼、ChecksumException 是碼找到了但資料校驗不過、FormatException 則是格式不支援。成功時回傳的 Result 物件封裝了整組解碼結果,一行 getText() 就能把內容取出來。

踩坑提醒

不少朋友抓下 demo 後會遇到 Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/google/zxing/BarcodeFormat;。這個錯誤跟程式邏輯無關,單純是專案裡放了兩份功能重複的 JAR,把多餘的那個刪掉即可。

原文轉自:https://blog.csdn.net/xiaanming/article/details/14450809

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