解码后的位图字节大小?

use*_*463 63 android bitmap

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

谢谢你的解决方案!

更新:getRowBytes*getHeight可能会成功.我将以这种方式实现它,直到有人提出反对它的东西.

use*_*463 114

getRowBytes() * getHeight() 似乎对我很好.

更新到我~2岁的答案:由于API级别12 Bitmap有直接查询字节大小的方法: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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • @Kalpesh你的三星有一个hdpi屏幕和moto xhdpi,所以它在这些模型上加载不同大小的资源.查看google display densitiy bucket doc. (3认同)

and*_*per 43

最好只使用支持库:

int bitmapByteCount=BitmapCompat.getAllocationByteCount(bitmap)
Run Code Online (Sandbox Code Playgroud)

  • 我使用 BitmapCompat.getAllocationByteCount(scaledBitmap) 获取分配字节数 3145728。但实际大小是207kB。我究竟做错了什么? (3认同)
  • @Sniper 真实尺寸是多少?如果您指的是文件大小,这是有道理的,因为文件是压缩的。如今,没有人会在不将图像编码为 JPG/PNG/WEBP 的情况下将其放入文件中。文件的大小不应与解码图像的大小相同。每个图像的估计字节数为“width*height*bytesPerPixel”,其中 bytesPerPixel 通常为 4 或 2。这意味着,如果您有 1000x1000 图像,则可能需要大约 4*1000*1000= 4,000,000 字节,即 ~4MB 。 (2认同)
  • @Sniper 您将图像文件发送到服务器。通常是 JPEG、PNG、WEBP...所有这些通常占用不到 5MB 的存储空间,因为它们经过压缩。它们占用的存储空间几乎总是比位图占用的内存少。只需使用 `file.length` 创建文件后检查文件大小:https://developer.android.com/reference/java/io/File.html#length() 。它与位图无关。位图分辨率可能很大也可能很小。你所说的是文件本身。 (2认同)

pat*_*ckf 21

这是使用KitKat的2014版本,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();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,结果可能大于重新使用位图来解码较小尺寸的其他位图或手动重新配置的结果.getAllocationByteCount() getByteCount()


ahm*_*_89 5

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

与@ user289463答案的唯一区别是使用getAllocationByteCount()KitKat及以上版本.

  • @Sniper 207kB 值是压缩文件存储在磁盘上时的大小。当它加载到内存中时,它会被解压缩并使用您从函数中获得的字节数。 (2认同)