我如何确定/计算使用 BitmapFactory 解码后位图的字节大小?
我需要知道它占用多少内存空间,因为我正在我的应用程序中进行内存缓存/管理。(文件大小不足以判断,因为这些是 jpg/png 文件)
感谢任何解决方案!
更新:getRowBytes * getHeight 可能会奏效... 我将采用这种方式实现,直到有人提出反对意见。
getRowBytes() * getHeight()
看起来对我来说已经很好了。 @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();
}
}
最好只使用支持库:
int bitmapByteCount=BitmapCompat.getAllocationByteCount(bitmap)
但是如果您的Android项目至少使用minSdk为19(即Kitkat,表示4.4),则可以直接使用bitmap.getAllocationByteCount()。
width*height*bytesPerPixel
,其中bytesPerPixel通常为4或2. 这意味着,如果您有一个1000x1000的图像,则可能需要约410001000= 4,000,000字节,即约4MB。 - android developerfile.length
检查创建后的文件大小即可:https://developer.android.com/reference/java/io/File.html#length()。这与位图无关。位图的分辨率可能很高或很低。你所说的是文件本身。 - android developer这是使用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();
}
}
getAllocationByteCount()
。
getAllocationByteCount()
的KitKat方法。请参阅http://developer.android.com/reference/android/graphics/Bitmap.html#getAllocationByteCount()。 - Itai Hanski