开发者

Bitmap byte-size after decoding?

开发者 https://www.devze.com 2022-12-22 03:29 出处:网络
How can I determine/calc开发者_高级运维ulate the byte size of a bitmap (after decoding with BitmapFactory)?

How can I determine/calc开发者_高级运维ulate the byte size of a bitmap (after decoding with BitmapFactory)? I need to know how much memory space it occupies, because I'm doing memory caching/management in my app. (file size is not enough, since these are jpg/png files)

Thanks for any solutions!

Update: getRowBytes * getHeight might do the trick.. I'll implement it this way until someone comes up with something against it.


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


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() .


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号