標籤:src 回收 roi .com 又能 ade 比例 識別 多次
續上一篇,開發圖片二維碼識別功能後,我們對功能進行效能分析記憶體佔用顯著提高了,不使用該功能記憶體佔用大約是147M,使用這個功能多次以後,高達203M。
因此對功能進行研究,發現每次產生的圖片沒有即時的釋放,導致記憶體中的圖片不斷累積,記憶體佔用不斷攀升。因此,需要對圖片進行釋放,釋放的時候需要特別關注的地方有:
1.釋放注意圖片的狀態。
2.注意異常的捕獲。
下面就是圖片釋放的有關代碼。
/** * 回收bitmap */ public static void recycleBitmap(Bitmap bitmap ) { if(bitmap != null && !bitmap.isRecycled()){ bitmap.recycle(); bitmap = null; } }
對於異常的捕獲主要是需要關注圖片在進行encode和decode過程中的處理,原來的方法應該改為如下:
public static Result handleQRCodeFormBitmap(Bitmap bitmap) { Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class); hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); hints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE); RGBLuminanceSource source = null; QRCodeReader reader2 = null; Result result = null; try { source = new RGBLuminanceSource(bitmap); BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source)); reader2 = new QRCodeReader(); result = reader2.decode(bitmap1, hints); } catch (Exception e) { e.printStackTrace(); if (source != null && reader2 != null) { BinaryBitmap bitmap2 = new BinaryBitmap(new GlobalHistogramBinarizer(source)); try { result = reader2.decode(bitmap2, hints); } catch (Exception e1) { e1.printStackTrace(); } } } return result; }
當然對於整個流程來說還有其他的最佳化方法,比如將儲存的圖片格式壓縮比例都進行調整,在不影響識別的前提下,將圖片進行處理,這樣既能節省cpu時間又能節省記憶體開銷。
如果大家有其他更好的方案,歡迎提出。
android 圖片二維碼識別和儲存(二)