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



使用设备相机后,我得到一个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;
    }

我在第一次尝试解码文件时收到一个巨大的内存不足错误:

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

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

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

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

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

with inJustDecodeBounds = true .你会得到一个空bitmap,但bitmapOptions对象将用位图的宽度和高度填充。那么它只是数学的。您需要 width * height * 4 个字节才能将位图保留在内存中

最新更新