1. 程式人生 > >android 圖片二維碼識別和保存(二)

android 圖片二維碼識別和保存(二)

-a rac CA bar binary 占用 我們 new ogr

續上一篇,開發圖片二維碼識別功能後,我們對功能進行性能分析內存占用顯著提高了,不使用該功能內存占用大約是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 圖片二維碼識別和保存(二)