[关闭]
@946898963 2020-02-28T04:03:47.000000Z 字数 5484 阅读 2087

计算Bitmap大小

Bitmap


今天做图像缓存需要计算Bitmap的所占的内存空间,于是研究了下Bitmap关于内存占用的API

1、getRowBytes:Since API Level 1,用于计算位图每一行所占用的内存字节数。

2、getByteCount:Since API Level 12,用于计算位图所占用的内存字节数。

查看Bitmap源码:

  1. public final int getByteCount() {
  2. return getRowBytes() * getHeight();
  3. }

也就是说位图所占用的内存空间数等于位图的每一行所占用的空间数乘以位图的行数。

获取Bitmap大小的工具方法:

  1. /**
  2. * 得到bitmap的大小
  3. */
  4. public static int getBitmapSize(Bitmap bitmap) {
  5. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //API 19
  6. return bitmap.getAllocationByteCount();
  7. }
  8. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12
  9. return bitmap.getByteCount();
  10. }
  11. // 在低版本中用一行的字节x高度
  12. return bitmap.getRowBytes() * bitmap.getHeight(); //earlier version
  13. }

getRowBytes调用的是native方法。

我们能不能给一张在某个手机上的图片,你就知道Bitmap所在内存的大小呢?为了探究Bitmap的奥秘,我们去手动计算一张Bitmap的大小。

下载了Android framework源码,Bitmap相关的源码在文件下:frameworks\base\core\jni\android\graphics,找到 Bitmap.cpp, getRowBytes() 对应的函数为:

  1. static jint Bitmap_rowBytes(JNIEnv* env, jobject, jlong bitmapHandle) {
  2. LocalScopedBitmap bitmap(bitmapHandle);
  3. return static_cast<jint>(bitmap->rowBytes());
  4. }

SkBitmap.cpp:

  1. size_t SkBitmap::ComputeRowBytes(Config c, int width) {
  2. return SkColorTypeMinRowBytes(SkBitmapConfigToColorType(c), width);
  3. }

SkImageInfo.h:

  1. static int SkColorTypeBytesPerPixel(SkColorType ct) {
  2. static const uint8_t gSize[] = {
  3. 0, // Unknown
  4. 1, // Alpha_8
  5. 2, // RGB_565
  6. 2, // ARGB_4444
  7. 4, // RGBA_8888
  8. 4, // BGRA_8888
  9. 1, // kIndex_8
  10. };
  11. SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gSize) == (size_t)(kLastEnum_SkColorType + 1),
  12. size_mismatch_with_SkColorType_enum);
  13. SkASSERT((size_t)ct < SK_ARRAY_COUNT(gSize));
  14. return gSize[ct];
  15. }
  16. static inline size_t SkColorTypeMinRowBytes(SkColorType ct, int width) {
  17. return width * SkColorTypeBytesPerPixel(ct);
  18. }

顺便提一下,Bitmap本质上是一个SKBitmap ,而这个SKBitmap也是大有来头,它来自Skia 。这个是Android 2D图像引擎,而且也是flutter的图像引擎。我们发现ARGB_8888(也就是我们最常用的Bitmap的格式)的一个像素占用4byte,那么rowBytes实际上就是4*widthbytes。那么一行图片所占的内存计算公式:

  1. 图片的占用内存 = 图片的长度(像素单位) * 图片的宽度(像素单位) * 单位像素所占字节数

但需要注意的是, 在使用decodeResource 获得的 Bitmap 的时候,上面的计算公式并不准确。让我们来看看原因。decodeStream 会调用 native 方法 nativeDecodeStream 最终会调用BitmapFactory.cpp 的 doDecode函数:

  1. static jobject doDecode(JNIEnv* env, SkStreamRewindable* stream, jobject padding, jobject options) {
  2. // .....省略
  3. if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
  4. //对应不同 dpi 的值不同,这个值跟这张图片的放置的目录有关,如 hdpi 是240;xdpi 是320;xxdpi 是480。
  5. const int density = env->GetIntField(options, gOptions_densityFieldID);
  6. //特定手机的屏幕像素密度不同,如华为p20 pro targetDensity是480
  7. const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
  8. const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
  9. if (density != 0 && targetDensity != 0 && density != screenDensity) {
  10. //缩放比例(这个是重点)
  11. scale = (float) targetDensity / density;
  12. }
  13. }
  14. }
  15. //这里这个deodingBitmap就是解码出来的bitmap,大小是图片原始的大小
  16. int scaledWidth = size.width();
  17. int scaledHeight = size.height();
  18. bool willScale = false;
  19. // Apply a fine scaling step if necessary.
  20. if (needsFineScale(codec->getInfo().dimensions(), size, sampleSize)) {
  21. willScale = true;
  22. scaledWidth = codec->getInfo().width() / sampleSize;
  23. scaledHeight = codec->getInfo().height() / sampleSize;
  24. }
  25. // Scale is necessary due to density differences.
  26. //进行缩放后的高度和宽度
  27. if (scale != 1.0f) {
  28. willScale = true;
  29. scaledWidth = static_cast<int>(scaledWidth * scale + 0.5f);//①
  30. scaledHeight = static_cast<int>(scaledHeight * scale + 0.5f);
  31. }
  32. //.......省略
  33. if (willScale) {
  34. // This is weird so let me explain: we could use the scale parameter
  35. // directly, but for historical reasons this is how the corresponding
  36. // Dalvik code has always behaved. We simply recreate the behavior here.
  37. // The result is slightly different from simply using scale because of
  38. // the 0.5f rounding bias applied when computing the target image size
  39. //sx 和 sy 实际上约等于 scale ,因为在①出可以看出scaledWidth 和 scaledHeight 是由 width 和 height 乘以 scale 得到的。
  40. const float sx = scaledWidth / float(decodingBitmap.width());
  41. const float sy = scaledHeight / float(decodingBitmap.height());
  42. // Set the allocator for the outputBitmap.
  43. SkBitmap::Allocator* outputAllocator;
  44. if (javaBitmap != nullptr) {
  45. outputAllocator = &recyclingAllocator;
  46. } else {
  47. outputAllocator = &defaultAllocator;
  48. }
  49. SkColorType scaledColorType = colorTypeForScaledOutput(decodingBitmap.colorType());
  50. // FIXME: If the alphaType is kUnpremul and the image has alpha, the
  51. // colors may not be correct, since Skia does not yet support drawing
  52. // to/from unpremultiplied bitmaps.
  53. outputBitmap.setInfo(
  54. bitmapInfo.makeWH(scaledWidth, scaledHeight).makeColorType(scaledColorType));
  55. if (!outputBitmap.tryAllocPixels(outputAllocator, NULL)) {
  56. // This should only fail on OOM. The recyclingAllocator should have
  57. // enough memory since we check this before decoding using the
  58. // scaleCheckingAllocator.
  59. return nullObjectReturn("allocation failed for scaled bitmap");
  60. }
  61. SkPaint paint;
  62. // kSrc_Mode instructs us to overwrite the uninitialized pixels in
  63. // outputBitmap. Otherwise we would blend by default, which is not
  64. // what we want.
  65. paint.setBlendMode(SkBlendMode::kSrc);
  66. paint.setFilterQuality(kLow_SkFilterQuality); // bilinear filtering
  67. SkCanvas canvas(outputBitmap, SkCanvas::ColorBehavior::kLegacy);
  68. canvas.scale(sx, sy);//canvas进行缩放
  69. canvas.drawBitmap(decodingBitmap, 0.0f, 0.0f, &paint);
  70. } else {
  71. outputBitmap.swap(decodingBitmap);
  72. }
  73. //.......省略
  74. }

所以,sx和sy约等于scale的值,而

  1. scale = (float) targetDensity / density

那么我们来计算,在一张4000 * 3000的jpg图片,我们把它放在drawable - xhdpi目录下,在华为 P20 Pro上加载,这个手机上densityDpi为480,用getByteCount算出占用内存为108000000。
我们来手动计算:

  1. sx = 480/320,
  2. sy = 480/320,
  3. 4000 * sx *3000 * sy * 4 = 108000000

如果你自己算你手机上的可能和getByteCount不一致,那是因为精度不一样,大家可以看到上面源码①处,

  1. scaledWidth = static_cast(scaledWidth * scale + 0.5f);

它是这样算的,所以我们可以用:

  1. scaledWidth = int 480/320 *4000 + 0.5
  2. scaledHeight = int 480/320 *3000 + 0.5

Bitmap所占内存空间为:scaledWidth * scaledHeight * 4所以这时Bitmap所占内存空间的方式为:

  1. 图片的占用内存 = 缩放后图片的长度(像素单位) * 缩放后图片的宽度(像素单位) * 单位像素所占字节数

总结:这个方法主要是让我们知道为什么同一张图片放在不同分辨率的文件下,Bitmap 所占内存空间的不同。而且这个计算方式是用decodeResource来得到Bitmap的大小时,才有效。而用decodeFile、decodeStream直接计算就行,没有缩放宽和高的整个过程。

参考链接:

Android 计算Bitmap大小 getRowBytes和getByteCount()

android Bitmap getByteCount和getRowBytes

深入理解Android Bitmap的各种操作

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注