Android BitmapFactory.decodeResource takes too much memory

android, bitmap, image, java, memory

Solution

OK, I resolved my problem in two steps:

1) According to Jim's answer I've added

android:largeHeap="true"

on my application tag in the `AndroidManifest.xml` file.

2) Image has been automatically resized because of high `DPI` of screen on my device. To avoid this I had to set inScaled option to false:

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap bm = BitmapFactory.decodeResource(getResources(), R.raw.test, options);

Thanks for all your answers.

Problem

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.

Original source