Android 计算Bitmap大小

今天使用LruCache写demo的时候,要获取Bitmap的大小

于是就用到了

 

return bitmap.getRowBytes() * bitmap.getHeight();// 获取大小并返回
//Bitmap所占用的内存空间数等于Bitmap的每一行所占用的空间数乘以Bitmap的行数


为什么不用bitmap.getByteCount()呢?
因为getByteCount要求的API版本较高,考虑到兼容性使用上面的方法


1、getRowBytes:Since API Level 1
2、getByteCount:Since API Level 12


查看Bitmap源码
  

[java] view plain copy
 
 print?
  1. public final int getByteCount() {  
  2.       return getRowBytes() * getHeight();  
  3.   }  


所以API 12 以后
getByteCount() = getRowBytes() * getHeight();


在计算Bitmap所占空间时上面的方法或许有帮助。

 

补充:

 

[java] view plain copy
 
 print?
    1. /** 
    2.   * 得到bitmap的大小 
    3.   */  
    4.  public static int getBitmapSize(Bitmap bitmap) {  
    5.      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {    //API 19  
    6.          return bitmap.getAllocationByteCount();  
    7.      }  
    8.      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12  
    9.          return bitmap.getByteCount();  
    10.      }  
    11.      // 在低版本中用一行的字节x高度  
    12.      return bitmap.getRowBytes() * bitmap.getHeight();                //earlier version  
    13.  }  
posted @ 2017-01-26 02:07  无天666  阅读(17661)  评论(0编辑  收藏  举报