Android Studio位图分配内存不足错误



我使用此函数旋转相机或图库中的位图:

public static Bitmap fixOrientation(Bitmap mBitmap) {
    if (mBitmap.getWidth() > mBitmap.getHeight()) {
        Matrix matrix = new Matrix();
        matrix.postRotate(90);
        return Bitmap.createBitmap(mBitmap , 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true); // the error is here!
    }
    return mBitmap;
}

在我使用它的前两次,它运行良好,但在第三次,它崩溃了应用程序,并给了我这个错误:

java.lang.OutOfMemoryError: Failed to allocate a 36578316 byte allocation with 16771872 free bytes and 29MB until OOM

这就是这个函数的调用位置:

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && data != null) {
        Uri uri = data.getData();
        try {
            Bitmap sourceBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
            Bitmap correctBitmap = fixOrientation(sourceBitmap);
            image.setImageBitmap(correctBitmap);
            bitmapsArray[cameraSideInt] = correctBitmap;
            chooseImageLayout.setVisibility(View.GONE);
            // show change layout
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

有人能想出解决这个错误的方法吗?

是的-不要保存那么多位图。你将它们存储在一个数组中。位图占用大量内存。当它们在该数组中时,不能对它们进行垃圾收集,这样内存就会丢失。你可能不应该这么做。

你可以在你的应用程序中查找其他内存泄漏,它们可能存在,并且可能会节省足够的内存来实现这一点。但这是个坏主意,尤其是如果位图很大(任何接近全屏的东西)。

最新更新