編輯:關於 Android 程式設計
本文示範如何在 Android 上產生並解析 QR Code,程式碼中附有逐行說明,並提供所需的 jar 檔供下載:二維碼Jar包.rar。
核心是 ZXing 的 QRCodeWriter:先把文字編碼成 BitMatrix,再逐像素轉成 Bitmap 顯示出來。這裡指定 CHARACTER_SET 為 utf-8,避免中文出現亂碼。
// 生成QR圖 private void createImage() { try { // 需要引入core包 QRCodeWriter writer = new QRCodeWriter(); String text = qr_text.getText().toString(); Log.i(TAG, "生成的文本:" + text); if (text == null || "".equals(text) || text.length() < 1) { return; } // 把輸入的文本轉為二維碼 BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT); System.out.println("w:" + martix.getWidth() + "h:" + martix.getHeight()); Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix bitMatrix = new QRCodeWriter().encode(text, 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; } } } Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT); qr_image.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } }
幾個實作細節值得留意:QR_WIDTH 與 QR_HEIGHT 建議直接對應輸出圖 desired 尺寸,因為 QR Code 是方形且放大後不失真;先在 hints 中指定編碼為 utf-8 再編碼,能避免中文被錯誤解讀;最後用 setPixels() 一次性寫入像素陣列,比逐點 setPixel() 快得多。
解析端流程是:取得 Bitmap → 轉成 RGBLuminanceSource → 用 HybridBinarizer 做二值化 → 交給 QRCodeReader 解碼。
// 解析QR圖片 private void scanningImage() { Map<DecodeHintType, String> hints = new HashMap<DecodeHintType, String>(); hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 獲得待解析的圖片 Bitmap bitmap = ((BitmapDrawable) qr_image.getDrawable()).getBitmap(); RGBLuminanceSource source = new RGBLuminanceSource(bitmap); BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source)); QRCodeReader reader = new QRCodeReader(); Result result; try { result = reader.decode(bitmap1, hints); // 得到解析後的文字 qr_result.setText(result.getText()); } catch (NotFoundException e) { e.printStackTrace(); } catch (ChecksumException e) { e.printStackTrace(); } catch (FormatException e) { e.printStackTrace(); } }
這裡的 HybridBinarizer 比預設的 GlobalHistogramBinarizer 更能應付光線不均勻的照片,實務上辨識率明顯更高。三個例外各有含義:NotFoundException 代表圖中找不到 QR Code 圖案,ChecksumException 代表解出的資料校驗失敗(通常是圖片模糊),FormatException 則代表資料格式不符 QR 規格。
以上就是 Android 上 QR Code 產生與解析的完整做法,希望對你的開發有所幫助。
Android 安全專項——Apk 加固實戰解析
原理部分這裡就不獻醜了,相關文章已講得很清楚,本文直接進入實戰,講述從零開始、最終實現加固的完整過程,其間踩過不少坑。 0x01 準備被加固的 Apk 第一步是建立要被加
Android AlertDialog 點擊外部自動消失的成因與兩個解法
開發時遇到一個惱人的現象:手指一碰到對話框以外的區域,它就自己關掉了。查了一下才發現,從 Android 4.0 開始,AlertDialog 的預設行為變了——點擊對話
Android UI 控件之菜單(Menu)全解
(一)概述 這一章來聊聊 Android 裡的 Menu。系統提供的菜單主要有三類: OptionMenu:選項菜單,最常見的一種,早期通過 Menu 鍵調出 SubM
深入拆解 Android 訊息處理機制:從 ThreadLocal 到 Handler 的完整鏈路
前言 關於 Android 的訊息處理機制,網路上已有大量分析文章。多數人讀完之後,都能說出 MessageQueue、Handler、Looper 三者大致如何協同運作