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

Android 二維碼實作:一般二維碼、中央 Logo 二維碼與掃描解析

編輯:關於 Android 程式設計

本文全程採用 Google 開源的 ZXing 框架,要實作的功能有三項:產生一般二維碼、產生中央帶 Logo 的二維碼,以及掃描解析二維碼。先看成果:

一、準備 ZXing 相關資源

首先需要一份 ZXing 的套件:

接著導入所需資源:

1、在 drawable 中放入 navbar.png
2、在 layout 中放入 camera.xml、main.xml、qrcode_capture_page.xml
3、建立 raw 資料夾並加入 beep.ogg 作為掃描提示音
4、合併 color.xml,並將 ids.xml 複製到 values 目錄

導入完成後的專案結構如下:

二、QRCodeUtil 工具類

package com.chinasie.barcodescanplugin;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * Created by HanWeijia on 2017/2/4.
 */
public class QRCodeUtil {

    private static int QR_WIDTH = 300;
    private static int QR_HEIGHT = 300;

    /**
     * 產生二維碼 Bitmap
     *
     * @param content  內容
     * @param widthPix 圖片寬度
     * @param heightPix 圖片高度
     * @param logoBm   二維碼中心的 Logo 圖示(可為 null)
     * @param filePath 用於儲存二維碼圖片的檔案路徑
     * @return 產生二維碼及存檔是否成功
     */
    public static Bitmap createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) {
        try {
            if (content == null || "".equals(content)) {
                return null;
            }

            // 設定參數
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 容錯等級
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 設定空白邊距寬度
            // hints.put(EncodeHintType.MARGIN, 2); // 預設為 4

            // 圖像資料轉換,使用矩陣轉換
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
            int[] pixels = new int[widthPix * heightPix];

            // 依二維碼演算法逐一產生像素,兩個 for 迴圈即為橫列掃描的結果
            for (int y = 0; y < heightPix; y++) {
                for (int x = 0; x < widthPix; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * widthPix + x] = 0xff000000;
                    } else {
                        pixels[y * widthPix + x] = 0xffffffff;
                    }
                }
            }

            // 產生二維碼圖片,使用 ARGB_8888 格式
            Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);

            if (logoBm != null) {
                bitmap = addLogo(bitmap, logoBm);
            }

            // 必須使用 compress 方法將 bitmap 存成檔案後再讀取。
            // 直接回傳的 bitmap 沒有任何壓縮,記憶體消耗龐大!
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 在二維碼中央加上 Logo 圖案 */
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (src == null) {
            return null;
        }
        if (logo == null) {
            return src;
        }

        // 取得圖片的寬高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }
        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }

        // logo 大小為二維碼整體的 1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);

        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);
            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }
        return bitmap;
    }

    /**
     * 產生一般二維碼
     *
     * @param url 要轉換的網址或字串,可以是中文
     */
    public static Bitmap createQRImage(String url) {
        try {
            // 判斷 URL 合法性
            if (url == null || "".equals(url) || url.length() < 1) {
                return null;
            }

            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            // 圖像資料轉換,使用矩陣轉換
            BitMatrix bitMatrix = new QRCodeWriter().encode(url, 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;
                    }
                }
            }

            // 產生二維碼圖片,使用 ARGB_8888 格式
            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
}

這個工具類的註解已經寫得相當清楚,重點在於容錯等級設為 H 之後,中央即使被 Logo 遮蓋仍能正常辨識。以下說明呼叫方式。

package com.chinasie.barcodescanplugin;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.zxing.activity.CaptureActivity;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static String TAB = MainActivity.class.getSimpleName();

    private EditText editText = null;   // 顯示掃描結果
    private Button btnScan = null;      // 掃描按鈕
    private ImageView imageNormal = null;   // 一般圖片
    private Button buttonNormal = null;     // 一般按鈕
    private Button buttonAndCenter = null;  // 帶中央圖片的按鈕
    private ImageView imageWithCenter = null; // 有中央圖片的圖片

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    /** 點擊事件回應 */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnScan:
                try {
                    // 開啟掃描介面,掃描條碼或二維碼
                    Intent openCameraIntent = new Intent(MainActivity.this, CaptureActivity.class);
                    startActivityForResult(openCameraIntent, 0);
                } catch (Exception ex) {
                    Log.e(TAB, ex.getMessage());
                    ex.printStackTrace();
                }
                break;

            case R.id.button:
                // 一般二維碼顯示到 ImageView 上
                imageNormal.setImageBitmap(QRCodeUtil.createQRImage("123456789"));
                break;

            case R.id.buttonAndCenter:
                final String filePath = File.separator + "qr_" + System.currentTimeMillis() + ".jpg";
                // 二維碼較大時,產生圖片與存檔可能較耗時,因此放在新執行緒中
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final Bitmap success = QRCodeUtil.createQRImage("strUrl", 800, 800,
                                BitmapFactory.decodeResource(getResources(), R.drawable.gg), filePath);
                        if (success != null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // 帶中央圖片的二維碼顯示在 imageWithCenter 上
                                    imageWithCenter.setImageBitmap(success);
                                }
                            });
                        }
                    }
                }).start();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 處理掃描結果並顯示於介面
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            editText.setText(scanResult);
        }
    }

    /** 初始化 View */
    private void initView() {
        editText = (EditText) this.findViewById(R.id.editText);
        imageWithCenter = (ImageView) findViewById(R.id.imageAndCenter);
        imageNormal = (ImageView) this.findViewById(R.id.image);
        btnScan = (Button) this.findViewById(R.id.btnScan);
        buttonNormal = (Button) this.findViewById(R.id.button);
        buttonAndCenter = (Button) findViewById(R.id.buttonAndCenter);

        btnScan.setOnClickListener(this);
        buttonNormal.setOnClickListener(this);
        buttonAndCenter.setOnClickListener(this);
    }
}

值得留意的是,尺寸較大又需要合成 Logo 的二維碼,產生與存檔都相當耗時,務必放在子執行緒中處理,再透過 runOnUiThread 回到主執行緒更新介面,否則容易觸發 ANR。

以上就是本文的全部內容,希望對大家有所幫助。

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