采样率,尺寸,fresco,通过c c++ 管理内存释放,lru(最少最近)算法强引用(原理)
BitmapFactory.Options的inSampleSize
参数,即采样率--尺寸压缩
官方文档指出采样率的取值应该是2的指数,例如k,那么采样后的图片宽高均为原图片大小的 1/k。
http://blog.csdn.net/linghu_java/article/details/8551887
关闭硬件加速,节省GPU的内存损耗
android:hardwareAccelerated="false"getWindow().setFlags(
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
图片压缩质量参数inPreferredConfig
A:透明度
R:红色
G:绿
B:蓝
Bitmap.Config ARGB_4444:每个像素占四位,即A=4,R=4,G=4,B=4,那么一个像素点占4+4+4+4=16位
Bitmap.Config ARGB_8888:每个像素占四位,即A=8,R=8,G=8,B=8,那么一个像素点占8+8+8+8=32位
Bitmap.Config RGB_565:每个像素占四位,即R=5,G=6,B=5,没有透明度,那么一个像素点占5+6+5=16位
Bitmap.Config ALPHA_8:每个像素占四位,只有透明度,没有颜色。
一般情况下我们都是使用的ARGB_8888,由此可知它是最占内存的,因为一个像素占32位,8位=1字节,所以一个像素占4字节的内存。假设有一张480x800的图片,如果格式为ARGB_8888,那么将会占用1500KB的内存。
bitmap.recycle();//2.3之前需要调用 |
當isPurgable設為true時,系統中內存不足時,可以回收部分Bitmap佔據的內存空間,這時一般不會出現OutOfMemory 錯誤。
在isPurgeable為false時表示創建的Bitmap的Pixel內存空間不能被回收,這樣BitmapFactory在不停decodeByteArray創建新的Bitmap對象,不同設備的內存不同,因此能夠同時創建的Bitmap個數可能有所不同,200個bitmap足以使大部分的設備重新OutOfMemory錯誤。
inPurgeable if true then 当Bitmap被回收后,如果又需要这个Bitmap时,会自动re-decode。因此inPurgeable 可以帮助系统节省内存,但是在快速滑动(ListView等)中不要使用,这样会增加GC负担,性能下降。如果是在fluid 和fast fly UI中建议使用inBitmap来减少内存消耗。这个属性在使用decodeResource和decodeFile的时候被忽略。
decodeStream/decodeResource
http://fly-ever.iteye.com/blog/1941986
inInputShareable:设置是否深拷贝,与inPurgeable结合使用,inPurgeable为false时,该参数无意义。
True: share a reference to the input data(inputStream, array,etc) 。 False :a deep copy
决定位图是否能够共享一个指向数据源的引用,或者是进行一份拷贝
opt.inPurgeable = true;
opt.inInputShareable = true;
这是我第二次看到这个方式,确实很神奇、有效。解决了90%以上的由于bitmap引起的oom问题
当我们实现了一个自定义的ImageRequest时,我们还利用 BitmapFactory.Options.inTempStorage. 参数进行了图片解码的优化。inTempStorege可以预申请一块内存,对所有解码过程中指定相同的内存,以达到减少临时内存的目的。
3.0以后引进了
BitmapFactory.Options.inBitmap
这个属性,如果option设置了这个属性的话,当load一张图片的时候,它将尝试去复用一张已经存在的图片:就是复用之前那种图片的内存,而不用频繁的去开辟/回收内存,从而提高了效率。
当然是有条件的:复用图片的大小必须和新生成的图片大小一致(确保所占用的内存一致)
http://architecture3.riaos.com/?p=3095422
- @TargetApi(VERSION_CODES.KITKAT)
- private static boolean canUseForInBitmap(Bitmap candidate,
- BitmapFactory.Options targetOptions) {
- // 4.4之前的版本,尺寸必须完全吻合
- if (Build.VERSION.SDK_INT < VERSION_CODES.KITKAT) {
- return candidate.getWidth() == targetOptions.outWidth
- && candidate.getHeight() == targetOptions.outHeight
- && targetOptions.inSampleSize == 1;
- }
- // 4.4版本,可以使用比自己大的bitmap
- int width = targetOptions.outWidth / targetOptions.inSampleSize;
- int height = targetOptions.outHeight / targetOptions.inSampleSize;
- // 根据图片格式,计算具体的bitmap大小
- int byteCount = width * height
- * getBytesPerPixel(candidate.getConfig());
- return byteCount <= candidate.getAllocationByteCount();
- }
if (cache != null) { // Try to find a bitmap to use for inBitmap. Bitmap inBitmap = cache.getBitmapFromReusableSet(options); if (inBitmap != null) { // If a suitable bitmap has been found, set it as the value of // inBitmap. options.inBitmap = inBitmap; } }