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

續上一篇,開發圖片二維碼識別功能後,咱們對功能進行性能分析內存佔用顯著提升了,不使用該功能內存佔用大約是147M,使用這個功能屢次之後,高達203M。性能

所以對功能進行研究,發現每次生成的圖片沒有即時的釋放,致使內存中的圖片不斷累積,內存佔用不斷攀升。所以,須要對圖片進行釋放,釋放的時候須要特別關注的地方有:優化

1.釋放注意圖片的狀態。spa

2.注意異常的捕獲。code

下面就是圖片釋放的有關代碼。orm

/**
     * 回收bitmap
     */
    public static void recycleBitmap(Bitmap bitmap ) {
        if(bitmap != null && !bitmap.isRecycled()){
            bitmap.recycle();
            bitmap = null;
        }
       
    }

對於異常的捕獲主要是須要關注圖片在進行encode和decode過程當中的處理,原來的方法應該改成以下:blog

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時間又能節省內存開銷。圖片

若是你們有其餘更好的方案,歡迎提出。內存

相關文章
相關標籤/搜索