2010-03-09 136 views
54

如何確定/計算位圖的字節大小(使用BitmapFactory解碼後)? 我需要知道它佔用了多少內存空間,因爲我在應用程序中進行內存緩存/管理。 (文件大小不夠,因爲這些都是jpg/png文件)解碼後位圖字節大小?

感謝您的任何解決方案!

更新:getRowBytes * getHeight可能會伎倆..我會這樣實現它,直到有人提出反對它的東西。

回答

108

getRowBytes() * getHeight()似乎對我很好。

更新了我的〜2歲的回答: 由於API級別12位圖有一個直接的方式來查詢字節大小: http://developer.android.com/reference/android/graphics/Bitmap.html#getByteCount%28%29

----示例代碼

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) 
    protected int sizeOf(Bitmap data) { 
     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) { 
      return data.getRowBytes() * data.getHeight(); 
     } else { 
      return data.getByteCount(); 
     } 
    } 
+0

試了一下這樣的: 原= BitmapFactory.decodeStream(getAssets()打開( 「hd.jpg」)); \t \t \t sizeOf(original); ByteArrayOutputStream out = new ByteArrayOutputStream(); \t \t original.compress(Bitmap.CompressFormat.WEBP,50,out); \t \t位圖解碼= BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray())); \t \t sizeOf(decode); 當我在你的方法中進行調試時,即使第二個圖像被壓縮,我也會得到相同的字節數!任何意見? – TharakaNirmana 2013-06-05 11:49:32

+1

@TharakaNirmana位圖總是包含未壓縮的圖像。壓縮僅用於縮小圖像以保存到文件。 – Ridcully 2013-07-10 19:58:09

+1

更新時間並添加'getAllocationByteCount()'的kitkat方法。看到http://developer.android.com/reference/android/graphics/Bitmap.html#getAllocationByteCount() – 2014-02-27 12:23:10

21

這裏2014版使用KitKat的getAllocationByteCount(),並編寫了這樣的編譯器瞭解版本邏輯(所以@TargetApi不需要)

/** 
* returns the bytesize of the give bitmap 
*/ 
public static int byteSizeOf(Bitmap bitmap) { 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
     return bitmap.getAllocationByteCount(); 
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { 
     return bitmap.getByteCount(); 
    } else { 
     return bitmap.getRowBytes() * bitmap.getHeight(); 
    } 
} 

請注意,getAllocationByteCount()的結果可以是大於getByteCount()的結果,如果重新使用位圖解碼其他較小尺寸的位圖或手動重新配置。

+0

是的,畢加索也用這個函數來計算位圖大小。 – wangzhengyi 2016-06-20 12:14:30

6
public static int sizeOf(Bitmap data) { 
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) { 
     return data.getRowBytes() * data.getHeight(); 
    } else if (Build.VERSION.SDK_INT<Build.VERSION_CODES.KITKAT){ 
     return data.getByteCount(); 
    } else{ 
     return data.getAllocationByteCount(); 
    } 
} 

與@ user289463答案的唯一區別,是KitKat及以上版本使用getAllocationByteCount()

29

它最好只使用支持庫:

int bitmapByteCount=BitmapCompat.getAllocationByteCount(bitmap) 
+0

好的!謝謝 – mbritto 2015-08-05 15:33:34