【发布时间】:2011-01-25 08:09:49
【问题描述】:
如何确定/计算位图的字节大小(使用 BitmapFactory 解码后)? 我需要知道它占用了多少内存空间,因为我正在我的应用程序中进行内存缓存/管理。 (文件大小不够,因为这些是 jpg/png 文件)
感谢您的任何解决方案!
更新:getRowBytes * getHeight 可能会成功。我会以这种方式实现它,直到有人提出反对意见。
【问题讨论】:
如何确定/计算位图的字节大小(使用 BitmapFactory 解码后)? 我需要知道它占用了多少内存空间,因为我正在我的应用程序中进行内存缓存/管理。 (文件大小不够,因为这些是 jpg/png 文件)
感谢您的任何解决方案!
更新:getRowBytes * getHeight 可能会成功。我会以这种方式实现它,直到有人提出反对意见。
【问题讨论】:
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();
}
}
【讨论】:
getAllocationByteCount()的kitkat方法了。见developer.android.com/reference/android/graphics/…
最好只使用支持库:
int bitmapByteCount=BitmapCompat.getAllocationByteCount(bitmap)
但如果你的 Android 项目至少使用 19 的 minSdk(kitkat,意思是 4.4),你可以只使用 bitmap.getAllocationByteCount() 。
【讨论】:
width*height*bytesPerPixel,其中 bytesPerPixel 通常为 4 或 2。这意味着,如果您有 1000x1000 图像,则可能需要大约 4*1000*1000= 4,000,000 字节,这意味着 ~4MB。
file.length : developer.android.com/reference/java/io/File.html#length() 创建文件后检查文件大小。它与位图无关。位图分辨率可能很大也可能很小。你说的是文件本身。
这是使用 KitKat 的 getAllocationByteCount() 的 2014 版本,其编写目的是让编译器理解版本逻辑(因此不需要 @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()的结果,如果一个位图被重新用于解码其他较小尺寸的位图,或者通过手动重新配置。
【讨论】:
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()。
【讨论】: