Returns the size of the allocated memory used to store this bitmap's pixels. - Android Graphics

Android examples for Graphics:Bitmap Size

Description

Returns the size of the allocated memory used to store this bitmap's pixels.

Demo Code


//package com.java2s;
import android.graphics.Bitmap;
import android.os.Build;

import java.lang.reflect.Field;

public class Main {
    private static volatile Field mBufferField;

    /**//w ww  .  j av  a 2s. c o m
     * Returns the size of the allocated memory used to store this bitmap's pixels.
     *
     * <p>This can be larger than the result of Bitmap.getByteCount() if a bitmap is reused to
     * decode other bitmaps of smaller size.</p>
     *
     * <p>This value will not change over the lifetime of a Bitmap.</p>
     *
     */
    public static int getAllocationByteCount(Bitmap bitmap) {
        if (null != bitmap) {
            Object buffer = null;
            try {
                if (null == mBufferField) {
                    mBufferField = Bitmap.class.getDeclaredField("mBuffer");
                    if (!mBufferField.isAccessible()) {
                        mBufferField.setAccessible(true);
                    }
                }

                buffer = mBufferField.get(bitmap);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            if (null == buffer || !buffer.getClass().isArray()) {
                // native backed bitmaps don't support reconfiguration,
                // so alloc size is always content size
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
                    return bitmap.getByteCount();
                } else {
                    return bitmap.getRowBytes() * bitmap.getHeight();
                }
            }
            return ((byte[]) buffer).length;
        }
        return -1;
    }
}

Related Tutorials