Bitmap降低内存使用方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ddxxii/article/details/80200722

bitmap是每个Android都会接触到的,虽然大部分情况下我们都会用图片框架来加载图片如glide,fresco等。当然推荐都使用对应框架来加载,官方也推荐使用glide来加载。

偶尔有时候我们也会直接从资源里加载,没用框架去加载它常用是从BitmapFactory类的三方方式来获取bitmap。

一. 采用适当压缩降低内存使用

  1. decodeByteArray(),从byte数组中解析出bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
  1. decodeFile(),从指定文件路径解析出bitmap
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
  1. decodeResource(), 从资源文件中解析出bitmap
Bitmap bitmap = BitmapFactory.decodeResource(res, resId);

初此之外,我们还可以在方法最后加一个BitmapFactory.Options参数,该参数会用于指定操作,比如缩放啊,抖动啊,宽高。

在我们没有指定option的时候,默认是没有这些处理的,会直接加载,在内存比较小的机器上,就可能出现OOM了,而且也造成了内存浪费,一个大分辨率的图片,没必要在一个小控件上完全展示,看起来也并没有特别的优点。所以咱们可以根据展示控件宽高来选择解析出的图片大小缩放,达到适度的降低内存使用。

  1. 处理方式:
/**
     * 从资源文件中获取压缩后的bitmap,根据宽高方式压缩
     *
     * @param res       资源
     * @param resId     资源id
     * @param reqWidth  需要的宽度
     * @param reqHeight 需要的高度
     * @return 压缩后的bitmap
     */
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                         int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        Log.i(TAG, "inSampleSize:" + options.inSampleSize);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    /**
     * 计算压缩大小
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    private static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

参考自官方文档:
有效装载大图

二. 采用重用降低内存分配

通过设置inBitmap参数,达到可以重用效果。记录下,不多讲,官方貌似也不推荐使用,地址

猜你喜欢

转载自blog.csdn.net/ddxxii/article/details/80200722
今日推荐