I have question about loading Bitmap from resources. My code:
public void onClick(View view) {
if (mainButton == view) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.test);
}
}
The test.jpg image resolution is 3288 x 4936px. It is jpeg (3,9MB / 48,7MB when uncompressed). While this function work (on my Nexus 7 2013 device), following exception occurs:
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)
Why application tries to allocate as much as 248MB? I wrote similar application in Qt for Android with the same image in resources and it works OK.
EDIT:
I can not resize it.
This is very simple application, like hello world. It does nothing else, just loads bitmap from resources.
EDIT2:
Jim's solution works for me. But there is another problem. After bitmap loading it is 4 times too big (2 times height and 2 times width). I've tried various images, including new image created in Pinta or Gimp.
You can use android:largeHeap="true" on your application tag in the AndroidManifest.xml file to go over the 64MB limit. This wont work on pre 3.0 devices.
That might fix your problem right there. If that's still not enough you can load the bitmap using native code where your heap limit is the full memory on the device. The NDK is more involved so try the above solution first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With