BitmapFactory解析与Bitmap的内存优化

转自:http://www.tuicool.com/articles/3eMNr2n


1、BitmapFactory解析Bitmap的原理

BitmapFactory提供的解析Bitmap的静态工厂方法有以下五种:

Bitmap decodeFile(...)
Bitmap decodeResource(...)
Bitmap decodeByteArray(...)
Bitmap decodeStream(...)
Bitmap decodeFileDescriptor(...)

其中常用的三个:decodeFile、decodeResource、decodeStream。decodeFile和decodeResource其实最终都是调用decodeStream方法来解析Bitmap,decodeStream的内部则是调用两个native方法解析Bitmap的:

nativeDecodeAsset()
nativeDecodeStream()

这两个native方法只是对应decodeFile和decodeResource、decodeStream来解析的,像decodeByteArray、decodeFileDescriptor也有专门的native方法负责解析Bitmap。

接下来就是看看这两个方法在解析Bitmap时究竟有什么区别decodeFile、decodeResource,查看后发现它们调用路径如下:

decodeFile->decodeStreamdecodeResource->decodeResourceStream->decodeStream

decodeResource在解析时多调用了一个 decodeResourceStream 方法,而这个decodeResourceStream方法代码如下:

public static Bitmap decodeResourceStream(Resources res, TypedValue value,
            InputStream is, Rect pad, Options opts) {
        if (opts == null) {
            opts = new Options();
        }
        if (opts.inDensity == 0 && value != null) {
            final int density = value.density;
            if (density == TypedValue.DENSITY_DEFAULT) {
                opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
            } else if (density != TypedValue.DENSITY_NONE) {
                opts.inDensity = density;
            }
        }
        if (opts.inTargetDensity == 0 && res != null) {
            opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
        }
        return decodeStream(is, pad, opts);
    }

它主要是对Options进行处理了,在得到 opts.inDensity 属性的前提下,如果我们没有对该属性设定值,那么将opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;赋定这个默认的Density值,这个默认值为160,为标准的dpi比例,即在Density=160的设备上1dp=1px,这个方法中还有这么一行

opts.inTargetDensity = res.getDisplayMetrics().densityDpi;

对 opts.inTargetDensity 进行了赋值,该值为当前设备的densityDpi值,所以说在decodeResourceStream方法中主要做了两件事:

1、对opts.inDensity赋值,没有则赋默认值1602、对opts.inTargetDensity赋值,没有则赋当前设备的densityDpi值

之后重点来了,之后参数将传入decodeStream方法,该方法中在调用native方法进行解析Bitmap后会调用这个方法setDensityFromOptions(bm, opts); :

private static void setDensityFromOptions(Bitmap outputBitmap, Options opts) {
        if (outputBitmap == null || opts == null) return;
        final int density = opts.inDensity;
        if (density != 0) {
            outputBitmap.setDensity(density);
            final int targetDensity = opts.inTargetDensity;
            if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) {
                return;
            }
            byte[] np = outputBitmap.getNinePatchChunk();
            final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
            if (opts.inScaled || isNinePatch) {
                outputBitmap.setDensity(targetDensity);
            }
        } else if (opts.inBitmap != null) {
            // bitmap was reused, ensure density is reset
            outputBitmap.setDensity(Bitmap.getDefaultDensity());
        }
    }

该方法主要就是把刚刚赋值过的两个属性inDensity和inTargetDensity给Bitmap进行赋值,不过并不是直接赋给Bitmap就完了,中间有个判断,当inDensity的值与inTargetDensity或与设备的屏幕Density不相等时,则将应用inTargetDensity的值,如果相等则应用inDensity的值。

所以总结来说, setDensityFromOptions 方法就是把 inTargetDensity 的值赋给Bitmap,不过前提是opts.inScaled = true;

进过上面的分析,可以得出这样一个结论:

在不配置Options的情况下:

1、decodeFile、decodeStream在解析时不会对Bitmap进行一系列的屏幕适配,解析出来的将是原始大小的图

2、decodeResource在解析时会对Bitmap根据当前设备屏幕像素密度densityDpi的值进行缩放适配操作,使得解析出来的Bitmap与当前设备的分辨率匹配,达到一个最佳的显示效果,并且Bitmap的大小将比原始的大

1.1、关于Density、分辨率、-hdpi等res目录之间的关系

DensityDpi分辨率resDensity
160dpi320×533mdpi1
240dpi480×800hdpi1.5
320dpi720×1280xhdpi2
480dpi1080×1920xxhdpi3
560dpi1440×2560xxxhdpi3.5

dp与px的换算公式为:

px = dp * Density

1.2、DisplayMetrics::densityDpi与density的区别

getResources().getDisplayMetrics().densityDpi——表示屏幕的像素密度

getResources().getDisplayMetrics().density——1dp等于多少个像素(px)

举个栗子:在屏幕密度为160的设备下,1dp=1px。在屏幕密度为320的设备下,1dp=2px。所以这就为什么在安卓中布局建议使用dp为单位,因为可以根据当前设备的屏幕密度动态的调整进行适配

2、Bitmap的优化策略

2.1、BitmapFactory.Options的属性解析

BitmapFactory.Options中有以下属性:

inBitmap——在解析Bitmap时重用该Bitmap,不过必须等大的Bitmap而且inMutable须为true
inMutable——配置Bitmap是否可以更改,比如:在Bitmap上隔几个像素加一条线段
inJustDecodeBounds——为true仅返回Bitmap的宽高等属性
inSampleSize——须>=1,表示Bitmap的压缩比例,如:inSampleSize=4,将返回一个是原始图的1/16大小的Bitmap
inPreferredConfig——Bitmap.Config.ARGB_8888等
inDither——是否抖动,默认为false
inPremultiplied——默认为true,一般不改变它的值
inDensity——Bitmap的像素密度
inTargetDensity——Bitmap最终的像素密度
inScreenDensity——当前屏幕的像素密度
inScaled——是否支持缩放,默认为true,当设置了这个,Bitmap将会以inTargetDensity的值进行缩放
inPurgeable——当存储Pixel的内存空间在系统内存不足时是否可以被回收
inInputShareable——inPurgeable为true情况下才生效,是否可以共享一个InputStream
inPreferQualityOverSpeed——为true则优先保证Bitmap质量其次是解码速度
outWidth——返回的Bitmap的宽
outHeight——返回的Bitmap的高
inTempStorage——解码时的临时空间,建议16*1024

2.2、优化策略

1、BitmapConfig的配置

2、使用decodeFile、decodeResource、decodeStream进行解析Bitmap时,配置inDensity和inTargetDensity,两者应该相等,值可以等于屏幕像素密度*0.75f

3、使用inJustDecodeBounds预判断Bitmap的大小及使用inSampleSize进行压缩

4、对Density>240的设备进行Bitmap的适配(缩放Density)

5、2.3版本inNativeAlloc的使用

6、4.4以下版本inPurgeable、inInputShareable的使用

7、Bitmap的回收

针对上面方案,把Bitmap解码的代码封装成了一个工具类,如下:

 
 
   
   
  1. package com.myframe.utils;
  2. import android.content.Context;
  3. import android.graphics.Bitmap;
  4. import android.graphics.BitmapFactory;
  5. import android.os.Build;
  6. import android.util.TypedValue;
  7. import java.io.FileInputStream;
  8. import java.io.FileNotFoundException;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.lang.reflect.Field;
  12. /**
  13. * Bitmap解码转换工具
  14. */
  15. public class BitmapDecodeUtil {
  16. private static final int DEFAULT_DENSITY = 240;
  17. private static final float SCALE_FACTOR = 0.75f;
  18. private static final Bitmap.Config DEFAULT_BITMAP_CONFIG = Bitmap.Config.RGB_565;
  19. /**
  20. * 获取优化的BitmapFactory.Options
  21. * @param context
  22. * @return
  23. */
  24. private static BitmapFactory.Options getBitmapOptions(Context context) {
  25. BitmapFactory.Options options = new BitmapFactory.Options();
  26. options.inScaled = true;
  27. options.inPreferredConfig = DEFAULT_BITMAP_CONFIG;
  28. options.inPurgeable = true;
  29. options.inInputShareable = true;
  30. options.inJustDecodeBounds = false;
  31. if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
  32. Field field = null;
  33. try {
  34. field = BitmapFactory.Options.class.getDeclaredField("inNativeAlloc");
  35. field.setAccessible(true);
  36. field.setBoolean(options, true);
  37. } catch (NoSuchFieldException e) {
  38. e.printStackTrace();
  39. } catch (IllegalAccessException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. int displayDensityDpi = context.getResources().getDisplayMetrics().densityDpi;
  44. float displayDensity = context.getResources().getDisplayMetrics().density;
  45. if (displayDensityDpi > DEFAULT_DENSITY && displayDensity > 1.5f) {
  46. int density = (int) (displayDensityDpi * SCALE_FACTOR);
  47. options.inDensity = density;
  48. options.inTargetDensity = density;
  49. }
  50. return options;
  51. }
  52. /**
  53. * 通过资源ID解码Bitmap
  54. * @param context
  55. * @param resId
  56. * @return
  57. */
  58. public static Bitmap decodeBitmap(Context context, int resId) {
  59. checkParam(context);
  60. return BitmapFactory.decodeResource(context.getResources(), resId, getBitmapOptions(context));
  61. }
  62. /**
  63. * 通过资源路径解码Bitmap
  64. * @param context
  65. * @param pathName
  66. * @return
  67. */
  68. public static Bitmap decodeBitmap(Context context, String pathName) {
  69. checkParam(context);
  70. return BitmapFactory.decodeFile(pathName, getBitmapOptions(context));
  71. }
  72. /**
  73. * 通过资源输入流解码Bitmap
  74. * @param context
  75. * @param is
  76. * @return
  77. */
  78. public static Bitmap decodeBitmap(Context context, InputStream is) {
  79. checkParam(context);
  80. checkParam(is);
  81. return BitmapFactory.decodeStream(is, null, getBitmapOptions(context));
  82. }
  83. /**
  84. * 通过资源ID获取压缩Bitmap
  85. * @param context
  86. * @param resId
  87. * @param maxWidth
  88. * @param maxHeight
  89. * @return
  90. */
  91. public static Bitmap compressBitmap(Context context, int resId, int maxWidth, int maxHeight) {
  92. checkParam(context);
  93. final TypedValue value = new TypedValue();
  94. InputStream is = null;
  95. try {
  96. is = context.getResources().openRawResource(resId, value);
  97. return compressBitmap(context, is, maxWidth, maxHeight);
  98. } catch (Exception e) {
  99. e.printStackTrace();
  100. } finally {
  101. if (is != null) {
  102. try {
  103. is.close();
  104. } catch (IOException e) {
  105. e.printStackTrace();
  106. }
  107. }
  108. }
  109. return null;
  110. }
  111. /**
  112. * 通过资源路径获取压缩Bitmap
  113. * @param context
  114. * @param pathName
  115. * @param maxWidth
  116. * @param maxHeight
  117. * @return
  118. */
  119. public static Bitmap compressBitmap(Context context, String pathName, int maxWidth, int maxHeight) {
  120. checkParam(context);
  121. InputStream is = null;
  122. try {
  123. is = new FileInputStream(pathName);
  124. return compressBitmap(context, is, maxWidth, maxHeight);
  125. } catch (FileNotFoundException e) {
  126. e.printStackTrace();
  127. } finally {
  128. if (is != null) {
  129. try {
  130. is.close();
  131. } catch (IOException e) {
  132. e.printStackTrace();
  133. }
  134. }
  135. }
  136. return null;
  137. }
  138. /**
  139. * 通过资源流获取压缩Bitmap
  140. * @param context
  141. * @param is
  142. * @param maxWidth
  143. * @param maxHeight
  144. * @return
  145. */
  146. public static Bitmap compressBitmap(Context context, InputStream is, int maxWidth, int maxHeight) {
  147. checkParam(context);
  148. checkParam(is);
  149. BitmapFactory.Options opt = new BitmapFactory.Options();
  150. opt.inJustDecodeBounds = true;
  151. BitmapFactory.decodeStream(is, null, opt);
  152. int height = opt.outHeight;
  153. int width = opt.outWidth;
  154. int sampleSize = computeSampleSize(width, height, maxWidth, maxHeight);
  155. BitmapFactory.Options options = getBitmapOptions(context);
  156. options.inSampleSize = sampleSize;
  157. return BitmapFactory.decodeStream(is, null, options);
  158. }
  159. /**
  160. * 计算SampleSize
  161. * @param width
  162. * @param height
  163. * @param maxWidth
  164. * @param maxHeight
  165. * @return
  166. */
  167. private static int computeSampleSize(int width, int height, int maxWidth, int maxHeight) {
  168. int inSampleSize = 1;
  169. if (height > maxHeight || width > maxWidth) {
  170. final int heightRate = Math.round((float) height / (float) maxHeight);
  171. final int widthRate = Math.round((float) width / (float) maxWidth);
  172. inSampleSize = heightRate < widthRate ? heightRate : widthRate;
  173. }
  174. if (inSampleSize % 2 != 0) {
  175. inSampleSize -= 1;
  176. }
  177. return inSampleSize <= 1 ? 1 : inSampleSize;
  178. }
  179. /**
  180. * 检查对象是否为空
  181. * @param param
  182. */
  183. private static void checkParam(Object param) {
  184. if (param == null)
  185. throw new NullPointerException();
  186. }
  187. }

主要有两类方法:

一、decodeBitmap:对Bitmap不压缩,但是会根据屏幕的密度合适的进行缩放压缩

二、compressBimtap:对Bitmap进行超过最大宽高的压缩,同时也会根据屏幕的密度合适的进行缩放压缩。

3、Bitmap优化前后性能对比

针对上面方案,做一下性能对比,图片大小为3.26M,分辨率为2048*2048有两台设备:

3.1、density为320的设备


3.2、density为560的设备


可以看到,都是加载同一图片,在高屏幕像素密度的设备下所需要的内存需要很大、载入内存中的Bitmap的宽高也因设备的屏幕像素密度也改变,正如上面分析的一样,使用decodeResource会自动适配当前设备的分辨率达到一个最佳效果,而只有这个方法会自动适配其它方法将不会,依次思路,我们在封装的工具类中在每一个方法都加入了依屏幕像素密度来自动适配,而在实际中并不需要那么高清的图片,所以我们可以根据设备的density来进行缩放,比如:在400>=density>240的情况下x0.8,在density>400的情况下x0.7,这样Bitmap所占用的内存将减少非常多,可以对面上面两个图片中bitmap和decodeBitmap两个值的大小,decodeBitmap只是对density进行了一定的缩放,而占用内存却减少非常多,而且显示效果也和原先的并无区别。之后对比我们进行了inSampleSize压缩的图片,进行压缩后的效果也看不出太大区别,而占用内存也减少了很多。

4、Bitmap的回收

4.1、Android 2.3.3(API 10)及以下的系统

在2.3以下的系统中,Bitmap的像素数据是存储在native中,Bitmap对象是存储在java堆中的,所以在回收Bitmap时,需要回收两个部分的空间:native和java堆。即先调用recycle()释放native中Bitmap的像素数据,再对Bitmap对象置null,保证GC对Bitmap对象的回收

4.2、Android 3.0(API 11)及以上的系统

在3.0以上的系统中,Bitmap的像素数据和对象本身都是存储在java堆中的,无需主动调用recycle(),只需将对象置null,由GC自动管理



  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值