处理大位图
我有一堆图像网址。我必须下载这些图像并将它们一一显示在我的应用程序中。我使用 SoftReferences
将图像保存在集合中,并将图像保存在 Sdcard 上,以避免重新获取并改善用户体验。
问题是我对位图的大小一无所知。事实证明,当我使用 BitmapFactory.decodeStream(InputStream) 方法时,我偶尔会遇到 OutOfMemoryExceptions 。因此,我选择使用 BitmapFactory Options(样本大小=2)对图像进行下采样。这提供了更好的输出:没有 OOM,但这会影响较小图像的质量。
此类情况我该如何处理?有没有办法选择性地仅对高分辨率图像进行下采样?
I have a bunch of image URLs. I have to download these images and display them in my application one-by-one. I am saving the images in a Collection using SoftReferences
and also on Sdcard to avoid refetches and improve user experience.
The problem is I dont know anything about the size of the bitmaps. And as it turns out, I am getting OutOfMemoryExceptions sporadically, when I am using BitmapFactory.decodeStream(InputStream)
method. So, I chose to downsample the images using BitmapFactory Options(sample size=2). This gave a better output: no OOMs, but this affects the quality of smaller images.
How should I handle such cases? Is there a way to selectively downsample only high resolution images?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
BitmapFactory.Options
类(我忽略了一个)中有一个名为inJustDecodeBounds
的选项,其 javadoc 如下:我用它来找出位图的实际大小,然后选择使用
inSampleSize
选项对其进行缩减采样。这至少可以避免解码文件时出现任何 OOM 错误。参考:
1. 处理更大的位图
2. 如何在解码之前获取位图信息
There is an option in
BitmapFactory.Options
class (one I overlooked) namedinJustDecodeBounds
, javadoc of which reads:I used it to find out the actual size of the Bitmap and then chose to down sample it using
inSampleSize
option. This at least avoids any OOM errors while decoding the file.Reference:
1. Handling larger Bitmaps
2. How do I get Bitmap info before I decode
经过几天的努力避免我在不同设备上遇到的所有 OutOfMemory 错误,我创建了这个:
此方法适用于我测试的所有设备,但我认为使用我不知道的其他过程可以更好的质量。
我希望我的代码可以帮助处于相同情况的其他开发人员。如果高级开发人员可以提供帮助,提供有关其他流程的建议,以避免流程中质量下降(降低),我也很感激。
After a few days struggling to avoid all OutOfMemory errors that I was getting with different devices, I create this:
This method works with all devices I tested, but I think the quality can be better using other process that I'm not aware.
I hope my code can help other developers in the same situation. I also appreciate if a senior developer can help, giving a suggestion about other process to avoid lose (less) quality in the process.
我自己所做的是:
inJustDecodeBounds
获取图像的原始大小,inSampleSize
(2 的幂,不会降低图像质量)。我使用这个函数:What I've done myself is :
inJustDecodeBounds
to get the original size of the imageinSampleSize
(a power of 2 that doesn't degrade the image quality). I use this function :