关于Bitmap中加载图片,防止OOM

   public Bitmap decodeSampledBitmapFromResource(int bitmapResourceId, int reqWidth, int reqHeight) {
        // 设置inJustDecodeBounds = true ,表示先不加载图片
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
//        BitmapFactory.decodeFile(file.getPath(), options);
        BitmapFactory.decodeResource(getResources(), bitmapResourceId, options);

        // 调用方法计算合适的 inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        // inJustDecodeBounds 置为 false 真正开始加载图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(getResources(), bitmapResourceId, options);
    }

    // 计算 BitmapFactpry 的 inSimpleSize的值的方法
    public int calculateInSampleSize(BitmapFactory.Options options,
                                     int reqWidth, int reqHeight) {
        if (reqWidth == 0 || reqHeight == 0) {
            return 1;
        }

        // 获取图片原生的宽和高
        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;
    }

关于图片的缩放

inputBitmap = Bitmap.createScaledBitmap(inputBitmap, inputSpaceWidth, inputSpaceHeight, true);

Bitmap.createScaledBitmap (Bitmap src, int dstWidth, int dstHeight, boolean filter);
src: The source bitmap.
dstWidth The new bitmap's desired width.
dstHeight The new bitmap's desired height.
filter true if the source should be filtered.

你可能感兴趣的:(关于Bitmap中加载图片,防止OOM)