Android 基於google Zxing實現對手機中的二維碼進行掃描

有時候我們有這樣子的需求,需要掃描手機中有二維碼的的圖片,所以今天實現的就是對手機中的二維碼圖片進行掃描,我這裏是直接在原來的工程上面加的這個功能,下面就簡單介紹下這個小功能的實現,首先我在界面上加了一個ImageButton,圖片還是用的微信的圖片,下面是掃描界面的title

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/mmtitle_bg_alpha" >

    <Button
        android:id="@+id/button_back"
        android:layout_width="75.0dip"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:background="@drawable/mm_title_back_btn"
        android:text="返回"
        android:textColor="@android:color/white" />

    <TextView
        android:id="@+id/textview_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:gravity="center_vertical"
        android:text="二維碼掃描"
        android:textColor="@android:color/white"
        android:textSize="18sp" />

    <ImageButton
        android:id="@+id/button_function"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="2dip"
        android:background="@drawable/mm_title_right_btn"
        android:minWidth="70dip"
        android:src="@drawable/mm_title_btn_menu_normal" />

</RelativeLayout>

在掃描界面MipcaActivityCapture對ImageButton對其點擊監聽,點擊ImageButton從手機中選擇圖片

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

在這裏使用了startActivityForResult來跳轉界面,當我們選中含有二維碼的圖片的時候會回調MipcaActivityCapture的onActivityResult方法,我們需要在onActivityResult方法裏面解析圖片中的二維碼

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            switch(requestCode){
            case REQUEST_CODE:
                //獲取選中圖片的路徑
                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();

                mProgress = new ProgressDialog(MipcaActivityCapture.this);
                mProgress.setMessage("正在掃描...");
                mProgress.setCancelable(false);
                mProgress.show();

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

                    }
                }).start();

                break;

            }
        }
    }

我們先通過圖片的Uri獲取圖片的路徑,然後根據圖片的路徑掃描出圖片裏面的二維碼內容,這將解碼圖片放在了一個子線程中,主要是防止因爲解析太久而出現ARN的情況
接下來看scanningImage(String path) 方法,zxing.jar中提供了對二維碼進行解析的類QRCodeReader.Java,使用decode(BinaryBitmap image, Map

    /**
     * 掃描二維碼圖片的方法
     * @param path
     * @return
     */
    public Result scanningImage(String path) {
        if(TextUtils.isEmpty(path)){
            return null;
        }
        Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
        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;
    }

Result是封裝瞭解碼的條碼圖像內的結果,我們只需要通過Result的getText()方法就能取出裏面的二維碼內容,這樣子我們就搞定了掃描手機中的二維碼圖片的小功能,接下來我們運行下項目,看看效果

這裏寫圖片描述

這裏寫圖片描述

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章