如何在从android中的文件路径解码位图之前检查潜在的文件大小/位图大小?

时间:2014-12-15 16:33:20

标签: android bitmap

使用设备相机后,我得到一个52MB的位图,我就这样解码:

    try {
        bitmapLarge = BitmapFactory.decodeFile(pathName, bitmapOptions);
    } catch (OutOfMemoryError ex) {
        ex.printStackTrace();
        try {
            bitmapOptions.inSampleSize = 2;
            bitmapOptions.inJustDecodeBounds = false;
            bitmapLarge = BitmapFactory.decodeFile(pathName, bitmapOptions);
            bitmapOptions.inSampleSize = 1;
        } catch (OutOfMemoryError ex2) {
            ex2.printStackTrace();
            try {
                bitmapOptions.inSampleSize = 4;
                bitmapOptions.inJustDecodeBounds = false;
                bitmapLarge = BitmapFactory.decodeFile(pathName, bitmapOptions);
            } catch (OutOfMemoryError ex3) {
                ex3.printStackTrace();
                bitmapOptions.inSampleSize = 8;
                bitmapOptions.inJustDecodeBounds = false;
                bitmapLarge = BitmapFactory.decodeFile(pathName, bitmapOptions);
                bitmapOptions.inSampleSize = 1;
            }
            bitmapOptions.inSampleSize = 1;
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.e("resizing bitmap", "#### NULL");
        bitmapLarge = null;
        return null;
    }

我在第一次尝试decodeFile时遇到了一个巨大的OutOfMemoryError:

12-15 18:24:24.393: E/dalvikvm-heap(12890): Out of memory on a 51916816-byte allocation.

在尝试对其进行任何操作之前,如何知道位图的大小?

即使这是可能的,我怎么解码它以某种方式下采样?

2 个答案:

答案 0 :(得分:3)

而不是bitmapOptions.inJustDecodeBounds = false;将其更改为true,您将获得图像的边界

您也应该阅读此内容http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

答案 1 :(得分:2)

inJustDecodeBounds = true。您将返回null bitmap,但bitmapOptions对象将填充Bitmap的宽度和高度。那么它只是数学..你需要width * height * 4个字节来保存你的位图