Android:“尝试使用回收的位图”临时位图错误
我的应用程序可以加载相当大的图像。为了节省内存,我尝试使用一个临时位图来加载,并使用另一个临时位图来加载转换后的最终图像:
.....
finalBitmap.recycle();
finalBitmap = null;
Bitmap tempBitmap = BitmapFactory.decodeStream(fin, ...);
finalBitmap = Bitmap.createBitmap(tempBitmap, ....);
imgview.setImageBitmap(finalBitmap);
.....
现在,我们已经完成了 tempBitmap,它只需要传输解码后的位图到 createBitmap 中的转换步骤。所以:
.....
tempBitmap.recycle();
tempBitmap = null;
.....
而且......它因“尝试使用回收的位图”错误而崩溃,特别是因为 tempBitmap 的回收。 tempBitmap 未显示,仅在此处使用。。
这里出了什么问题?我应该在整个过程中使用“finalBitmap”并依靠 createBitmap 来管理它(finalBitmap = Bitmap.createBitmap (finalBitmap,....))?我看不出对 tempBitmap 的持续依赖会导致这样的失败。
编辑:是的,空赋值似乎会导致适当的、最终垃圾回收,但我很困惑为什么临时位图上的 recycle() 如此有问题在这种情况下。我的印象是 createBitmap() 持有对它的引用,但为什么,以及持续多长时间?
My app can load quite large images. In an effort to be memory-conservative, I'm attempting to use a temporary bitmap to load and another for the final image after transformation:
.....
finalBitmap.recycle();
finalBitmap = null;
Bitmap tempBitmap = BitmapFactory.decodeStream(fin, ...);
finalBitmap = Bitmap.createBitmap(tempBitmap, ....);
imgview.setImageBitmap(finalBitmap);
.....
Now, at this point we're done with tempBitmap, which was only needed to transport the decoded Bitmap to the transformation step in createBitmap. So:
.....
tempBitmap.recycle();
tempBitmap = null;
.....
And... it crashes with a "trying to use a recycled bitmap" error specifically because of the recycling of tempBitmap. tempBitmap wasn't displayed and is only used right there.
What's going wrong here? Should I just use "finalBitmap" throughout and rely on createBitmap to manage it (finalBitmap = Bitmap.createBitmap(finalBitmap , ....))? I fail to see what ongoing dependency on tempBitmap there would be that would cause such a failure.
Edit: Yes, the null assignment seems to result in the appropriate, eventual garbage collection, but I'm mystified as to why recycle() on a temp Bitmap is so problematic in this case. I get the impression that createBitmap() is holding a reference to it but why, and for how long?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
直接来自 Android
看来 createBitmap 函数有可能重新使用您提供的位图。如果是这种情况,那么您不应该回收临时位图,因为您的最终位图正在使用它。您可以做的一件事是
,仅当 tempBitmap 与 FinalBitmap 不同时才回收它。至少这似乎是文档所暗示的。
Straight from the Android documentation:
It seems that the createBitmap functions have the potential to re-use the bitmap that you provided. If that is the case, then you shouldn't recycle the temporary bitmap since your final bitmap is using it. One thing you can do is
That should only recycle the tempBitmap when it isn't the same as the finalBitmap. At least that seems to be what the documentation is implying.