项目开发中难免会用到图片资源加载,android本身提供了图片解析功能BitmapFactory,里面有多种多样的解析方案,不赘述了,写这篇文章主要是因为遇到了一个比较难懂的问题,分享出来大家如果知道原因请回复。
1)最简单的加载方案肯定就是decodestream了,我们把图片资源放到assets文件夹下,程序运行过程中通过assetsmanager打开流进行加载资源,可以得到bitmap对象,当然这种手段是最简单的一种方案。
2)有时候我们会遇到一些大的图片加载,那么大图片加载必然会出现内存问题,这时候我们就要考虑到图片加载带来的内存消耗隐患包括会出现oom问题,解决之道当然在于另一个重载函数decodestream,参数有三个
/**
* Decode an input stream into a bitmap. If the input stream is null, or
* cannot be used to decode a bitmap, the function returns null.
* The stream's position will be where ever it was after the encoded data
* was read.
*
* @param is The input stream that holds the raw data to be decoded into a
* bitmap.
* @param outPadding If not null, return the padding rect for the bitmap if
* it exists, otherwise set padding to [-1,-1,-1,-1]. If
* no bitmap is returned (null) then padding is
* unchanged.
* @param opts null-ok; Options that control downsampling and whether the
* image should be completely decoded, or just is size returned.
* @return The decoded bitmap, or null if the image data could not be
* decoded, or, if opts is non-null, if opts requested only the
* size be returned (in opts.outWidth and opts.outHeight)
*/
public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
}
为啥说这个呢,大家主要是看看这三个参数介绍,最重要是最后的options,很明显,android在设定之初已经考虑到了一些特殊加载情况,预留了里面的一些设置给开发者。具体如何使用设置不说了,百度很多介绍的,不搬别人文章了。
3)问题来了,大家有没有开发时候看源码的习惯,我在开发过程中有这样一个需求,要求程序本身自带一部分资源,然后sd卡在远程服务器下载一部分资源,当然这些是另一个问题,不多说,然后加载资源到程序中,运行。本人尝试加载assets文件夹下同样的图片资源,没任何问题,sd卡下的却出现了内存溢出oom,费解,本以为是自己代码有问题,审查了很久,还是看不出来,所以发帖求助了下,帖子链接http://bbs.youkuaiyun.com/topics/390582798?page=1#post-395493113帖子中已经提及了解决方案,并且附加了sdk源码,费解的是android加载流资源为什么sd卡流处理和assets流处理采取了不同的方案,其实有说明,只是我不太懂,如果有清楚的朋友欢迎探讨跟帖!