編輯:關於 Android 程式設計
二維碼幾乎無所不在——從支付、名片到活動報到,處處可見。本文從二維碼的原理談起,帶你用 Google 的 zxing 庫在 Android 上完成生成、辨識與相機掃描三件事。
二維碼是在平面(二維方向)上按特定規律分布的黑白圖形,用來記錄資料符號。它在編碼上巧妙運用了電腦內部「0」與「1」的比特流概念,用與二進位對應的幾何圖形來表示文字數值,再透過掃描設備自動讀取,達到資訊自動處理的目的。每種碼制都有特定的字符集、字元寬度與校驗機制,還具備對不同行的自動識別與抗圖形旋轉的能力。
其實二維碼與一維條碼本質類似,就像一維陣列與二維陣列的關係。最常見的一維碼就是食品與書本後面的條碼,起源於 20 世紀 40 年代,1970 年代 UPC 碼問世後開始廣泛應用於食品包裝。
為了讓 Java/Android 能輕鬆處理條碼,Google 開發了 zxing 庫:
https://github.com/zxing/zxing
zxing 支援多種條碼格式,這裡我們用常見的 QR_CODE(也就是微信裡看到的那種)。以下程式會在一條背景執行緒中產生二維碼並回傳 Bitmap:
public class EncodeThread { public static void encode(final String url, final int width, final int height, final EncodeResult result) { if (result == null) { return; } if (TextUtils.isEmpty(url)) { result.onEncodeResult(null); return; } new Thread() { @Override public void run() { try { MultiFormatWriter writer = new MultiFormatWriter(); Hashtable<EncodeHintType, String> hints = new Hashtable<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix bitMatrix = writer.encode(url, BarcodeFormat.QR_CODE, width, height, hints); Bitmap bitmap = parseBitMatrix(bitMatrix); result.onEncodeResult(bitmap); return; } catch (WriterException e) { e.printStackTrace(); } result.onEncodeResult(null); } }.start(); } public static Bitmap parseBitMatrix(BitMatrix matrix) { final int QR_WIDTH = matrix.getWidth(); final int QR_HEIGHT = matrix.getHeight(); 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 (matrix.get(x, y)) { pixels[y * QR_WIDTH + x] = 0xff000000; } else { pixels[y * QR_WIDTH + x] = 0xffffffff; } } } 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; } public interface EncodeResult { void onEncodeResult(Bitmap bitmap); } }
MultiFormatWriter 是個工具類,內部依格式分派給對應的 Writer(QR_CODE 對應 QRCodeWriter)。而 parseBitMatrix 則是逐點判斷矩陣的黑白,把每個點填成黑或白,最後組成一張二維碼圖片。
要從一張圖片還原出內容,用 MultiFormatReader 即可,它會依序嘗試各種格式的 Reader,直到成功為止:
public class ReDecodeThread { public static void encode(final Bitmap bitmap, final ReDecodeThreadResult listener) { if (listener == null) { return; } if (bitmap == null) { listener.onReDecodeResult(null); return; } new Thread() { @Override public void run() { try { MultiFormatReader multiFormatReader = new MultiFormatReader(); BitmapLuminanceSource source = new BitmapLuminanceSource(bitmap); BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source)); Result result1 = multiFormatReader.decode(bitmap1); listener.onReDecodeResult(result1.getText()); return; } catch (NotFoundException e) { e.printStackTrace(); } listener.onReDecodeResult(null); } }.start(); } public interface ReDecodeThreadResult { void onReDecodeResult(String url); } }
辨識前得先把 Bitmap 轉成亮度矩陣,這由 BitmapLuminanceSource 負責——它把每個像素換算成灰階值,供後續二ization 使用:
public final class BitmapLuminanceSource extends LuminanceSource{ private final byte[] luminances; public BitmapLuminanceSource(String path) throws FileNotFoundException { this(loadBitmap(path)); } public BitmapLuminanceSource(Bitmap bitmap) { super(bitmap.getWidth(), bitmap.getHeight()); int width = bitmap.getWidth(); int height = bitmap.getHeight(); int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); luminances = new byte[width * height]; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { int pixel = pixels[offset + x]; int r = (pixel >> 16) & 0xff; int g = (pixel >> 8) & 0xff; int b = pixel & 0xff; if (r == g && g == b) { luminances[offset + x] = (byte) r; } else { luminances[offset + x] = (byte) ((r + g + g + b) >> 2); } } } } @Override public byte[] getRow(int y, byte[] row) { if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Requested row is outside the image: " + y); } int width = getWidth(); if (row == null || row.length < width) { row = new byte[width]; } System.arraycopy(luminances, y * width, row, 0, width); return row; } @Override public byte[] getMatrix() { return luminances; } private static Bitmap loadBitmap(String path) throws FileNotFoundException { Bitmap bitmap = BitmapFactory.decodeFile(path); if (bitmap == null) { throw new FileNotFoundException("Couldn't open " + path); } return bitmap; } }
掃描比單純辨識只多一步:把相機預覽畫面直接轉換後辨識。首先把相機預覽資料導向 callback:
public void requestPreviewFrame(Handler handler, int message) { if (camera != null && previewing) { previewCallback.setHandler(handler, message); if (useOneShotPreviewCallback) { camera.setOneShotPreviewCallback(previewCallback); } else { camera.setPreviewCallback(previewCallback); } } }
預覽資料透過 callback 以 Handler 傳出去:
final class PreviewCallback implements Camera.PreviewCallback public void onPreviewFrame(byte[] data, Camera camera) { Point cameraResolution = configManager.getCameraResolution(); if (!useOneShotPreviewCallback) { camera.setPreviewCallback(null); } if (previewHandler != null) { Message message = previewHandler.obtainMessage(previewMessage, cameraResolution.x, cameraResolution.y, data); message.sendToTarget(); previewHandler = null; } else { Log.d(TAG, "Got preview callback, but no handler for it"); } }
收到訊息後進行解碼。這裡有個關鍵細節:由於資料方向問題,需要先把 byte 陣列旋轉,再交給建構的 BinaryBitmap 去辨識:
private void decode(byte[] data, int width, int height) { long start = System.currentTimeMillis(); Result rawResult = null; byte[] rotatedData = new byte[data.length]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) rotatedData[x * height + height - y - 1] = data[x + y * width]; } int tmp = width; width = height; height = tmp; PlanarYUVLuminanceSource source = CameraManager.get().buildLuminanceSource(rotatedData, width, height); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); try { rawResult = multiFormatReader.decodeWithState(bitmap); } catch (ReaderException re) { } finally { multiFormatReader.reset(); } if (rawResult != null) { Message message = Message.obtain(activity.getHandler(), R.id.decode_succeeded, rawResult); Bundle bundle = new Bundle(); bundle.putParcelable(DecodeThread.BARCODE_BITMAP, source.renderCroppedGreyscaleBitmap()); message.setData(bundle); message.sendToTarget(); } else { Message message = Message.obtain(activity.getHandler(), R.id.decode_failed); message.sendToTarget(); } }
一旦把相機畫面轉成 BinaryBitmap,剩下的辨識流程就和處理靜態圖片完全相同了。
Android Studio 應用效能優化:記憶體洩漏排查
問題場景 應用程式在頁面跳轉後出現卡頓,但未直接崩潰。這類問題常與記憶體使用、物件洩漏或背景任務未停止有關。 使用 Android Studio Memory 分析 A
Android Studio 開發環境配置經驗總結
自學安卓,不管用 Eclipse 還是 Android Studio,都離不開和 Android SDK 打交道。身為一名安卓新手,當初剛開始裝環境時被各種瑣碎問題折騰得
Android 中使用 shape 標籤的屬性詳解
shape 標籤常用的屬性有: - corners —— 圓角 - padding —— 內邊距 - size(height、width)—— 設定寬高 - stroke
Android 浮動視圖實作:跟手拖曳並自動貼邊的互動效果
浮動式 View 常見於懸浮按鈕、客服入口或快捷操作。要實作跟隨手指拖動並自動貼邊的效果,可以讓自訂 View 繼承 ImageView,並在 onTouch 中處理 A