BitmapFactory.decodeFile returns null 正确的文件

BitmapFactory.decodeFile returns null with a proper file

我正在尝试让简单的 decodeFile 工作,但我正在失去理智。

下面的代码 returns null 而 logcat 表示:D/skia﹕ --- decoder->decode returned false Aldo 有时会成功(50 次中有一次)。

try {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inDither = true;
        opt.inPreferredConfig = Bitmap.Config.ARGB_8888;

        canvasBitmap = BitmapFactory.decodeFile(myFile.getAbsolutePath(), opt);

    } catch (OutOfMemoryError e) {
        Log.d(TAG, "Trace: " + e);

        System.gc();

        try {
            Log.d(TAG, "Trying again");
            canvasBitmap = BitmapFactory.decodeFile(myFile.getAbsolutePath());
        } catch (OutOfMemoryError e2) {
            Log.d(TAG, "Trace: " + e2);
            Log.d(TAG, "Out of memory!!!!!!!");
        }
    }

文件已定义和getAbsolutePathreturns/storage/emulated/0/Pictures/Screenshots/Screenshot_2015-07-28-16-18-56.png

该文件基本上是在 phone 上截取的屏幕截图,它可以在图库应用程序和 PC 上正常打开,因此 没有损坏

如果由于某种原因这行不通,是否有任何带有自己的解码器的自定义库?我尝试了几个库,但它们似乎都使用相同的 decodeFile。

我正在 nexus 4 上进行测试,所以图像是 760p。

重试 decodeFile() 毫无意义。因为如果没有足够的可用内存来构建位图,decodeFile() 将 return 为 null。除了 return 值 null 之外,您不会收到其他警告。所以只需检查是否为空; –

我通过添加一个带有 if else

while 循环解决了这个问题

以下代码:

    BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inDither = true;
            opt.inPreferredConfig = Bitmap.Config.ARGB_8888;

            int i = 0;
            while (canvasBitmap == null && ++i < 99) {

                System.gc();

                Log.d(TAG, "Trying again: " + i);
                canvasBitmap = BitmapFactory.decodeFile(myFile.getAbsolutePath(), opt);
            }

它似乎效率很低但有效,我也在主线程之外 运行 它不会导致任何无响应行为。