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时间又能节省内存开销。图片

若是你们有其余更好的方案,欢迎提出。内存

相关文章
相关标签/搜索