Android BitmapFactory.decodeResource需要太多内存

jas*_*mar 3 java memory android image bitmap

我有关于从资源加载Bitmap的问题.我的代码:

public void onClick(View view) {
    if (mainButton == view) {
        Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.test);
    }
}
Run Code Online (Sandbox Code Playgroud)

test.jpg图像分辨率为3288 x 4936px.它是jpeg(未压缩时为3,9MB/48,7MB).虽然此功能有效(在我的Nexus 7 2013设备上),但会发生以下异常:

java.lang.OutOfMemoryError: Failed to allocate a 259673100 byte allocation with 5222644 free bytes and 184MB until OOM
        at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
        at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
        at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
        at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
        at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:467)
        at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:497)
        at pl.jaskol.androidtest.MainActivity.onClick(MainActivity.java:50)
        at android.view.View.performClick(View.java:4756)
        at android.view.View$PerformClick.run(View.java:19749)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Run Code Online (Sandbox Code Playgroud)

为什么应用程序尝试分配多达248MB?我在Qt for Android中编写了类似的应用程序,在资源中使用相同的图像并且工作正常.

编辑:

  1. 我无法调整它的大小.

  2. 这是一个非常简单的应用程序,比如hello world.它没有别的,只是从资源加载位图.

EDIT2:

吉姆的解决方案适合我.但还有另一个问题.在位图加载后,它是4倍太大(2倍高度和2倍宽度).我尝试了各种图像,包括在Pinta或Gimp中创建的新图像.

Jim*_*Jim 5

您可以android:largeHeap="true"AndroidManifest.xml文件中的应用程序标记上使用超出64MB限制.这不适用于pre 3.0设备.

这可能会解决你的问题.如果仍然不够,您可以使用本机代码加载位图,其中堆限制是设备上的完整内存.该NDK更多地参与所以首先尝试上面的解决方案.