解码后的位图字节大小?

如何确定/计算位图的字节大小(使用 BitmapFactory 解码后) ? 我需要知道它占用了多少内存空间,因为我正在我的应用程序中进行内存缓存/管理。(文件大小不够,因为这些是 jpg/png 文件)

谢谢你的解答!

更新: getRowBytes * getHeight 可能会起作用。.我会用这种方法实现,直到有人想出对策。

80076 次浏览

getRowBytes() * getHeight() seems to be working fine to me.

Update to my ~2 year old answer: Since API level 12 Bitmap has a direct way to query the byte size: http://developer.android.com/reference/android/graphics/Bitmap.html#getByteCount%28%29

----Sample code

    @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();
}
}

Here is the 2014 version that utilizes KitKat's getAllocationByteCount() and is written so that the compiler understands the version logic (so @TargetApi is not needed)

/**
* 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();
}
}

Note that the result of getAllocationByteCount() can be larger than the result of getByteCount() if a bitmap is reused to decode other bitmaps of smaller size, or by manual reconfiguration.

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();
}
}

The only difference with @user289463 answer, is the use of getAllocationByteCount() for KitKat and above versions.

It's best to just use the support library:

int bitmapByteCount=BitmapCompat.getAllocationByteCount(bitmap)

But if you have the Android project to use at least minSdk of 19 (kitkat, meaning 4.4), you can just use bitmap.getAllocationByteCount() .