android 本地大图片造成内存溢出的解决方案

在使用中,小的图片,可以通过drawable直接引用setImageResource或者setBackgroundResource, 但涉及到大图时,尽量通过decodeStream来创建bitmap,然后再给对应的view使用。

public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

原因:setImageResource方法,最终都是通过java层的createBitmap来完成的,需要消耗更多内存。

          而decodeStream最大的秘密在于其直接调用JNI>>nativeDecodeAsset()来完成decode,无需再使用java层的createBitmap,从而节省了java层的空间。

猜你喜欢

转载自blog.csdn.net/fuweng886/article/details/83415184