Java Android BitmapFactory.decodeResource占用太多内存
我对从参考资料中加载位图有疑问。我的代码:Java Android BitmapFactory.decodeResource占用太多内存,java,android,image,memory,bitmap,Java,Android,Image,Memory,Bitmap,我对从参考资料中加载位图有疑问。我的代码: public void onClick(View view) { if (mainButton == view) { Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.test); } } test.jpg图像分辨率为3288 x 4936px。它是jpeg(未压缩时为3,9MB/48,7MB)。此功能工作时(在我的Nexus 7 2
public void onClick(View view) {
if (mainButton == view) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.test);
}
}
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)
为什么应用程序尝试分配多达248MB的内存?
我在Qt中为Android编写了类似的应用程序,在参考资料中使用了相同的图像,效果良好
编辑:
吉姆的解决办法对我有效。但还有另一个问题。加载位图后,它太大了4倍(2倍高度和2倍宽度)。我尝试了各种图像,包括在Pinta或Gimp中创建的新图像。查看此资源:
尤其是
decodeSampledBitmapFromResource
方法。您可以在AndroidManifest.xml
文件中的应用程序标记上使用android:largeHeap=“true”
,以超过64MB
限制。这在3.0之前的设备上不起作用
这可能会解决你的问题。如果这还不够,可以使用本机代码加载位图,其中堆限制是设备上的全部内存。NDK
更复杂,因此请先尝试上述解决方案。好的,我通过两个步骤解决了问题:
1) 根据吉姆的回答,我加了一句
android:largeHeap="true"
在AndroidManifest.xml
文件中的我的应用程序标记上
2) 由于我的设备上屏幕的DPI较高,图像已自动调整大小。为了避免这种情况,我必须将inScaled选项设置为false:
谢谢您的回答。尝试在生成位图时在其上应用一些选项来更改样本大小。该图像“仅”需要约64MB(几乎每部手机都会失败)。你肯定在别的地方用了更多的内存。请添加相关代码。有趣的是,失败的内存请求正好是位图的4倍。我无法调整它的大小。我必须修改并保存。不幸的是,我必须以完全分辨率加载文件。然后您将需要使用NDK。所有Java对象都是在堆上创建的,这只提供了256MB的最大值,大约是OPs单个请求的大小。在许多设备上,您只能获得64MB或128MB。此解决方案不正确。你的应用程序内存泄漏。此解决方案只会延迟问题,但不会修复泄漏。试着找出你在图书馆“LeakCanary”的问题@MartinVonMartinsgrün你为什么这么说?259673100字节的分配不是内存泄漏-该大小与比例因子为2的图像完全匹配
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.raw.test, options);