Android中一张图片占内存多大
Mr.wu edited this page Apr 12, 2017
·
3 revisions
1、图片的像素点个数
2、单位像素占用的字节数
3、其中图片的像素点个数是图片的宽度与调试的积,所以一张图片占用的内存值为:
图片长度 * 图片宽度 * 单位像素占用的字节数
ALPHA_8只存储透明度信息而无颜色值;
ARGB_8888是指把每个像素点的透明度、R、G、B色值都用一个byte来表示,即需要4字节的空间来存储一个像素点的颜色信息。
RGB_565:仅需要2个字节的空间来存储每个像素点颜色信息,是由于它不存储像素点的透明度,而且使用5比特表示R色值,6比特表示G色值,5比特表示B色值。
由上可以看出,对同一张图片进行解码时,使用RGB_565的解码方式所占用的内容空间仅仅是ARGB_8888方式的50%。
Bitmap.getRowBytes()返回Bitmap中每一行像素点所占用的字节数,所以其值与Bitmap.getHeight()的积即为图片解码后所占用的内存空间值。
// MyImageView img = (MyImageView)findViewById(R.id.img);
Drawable drawable = img.getDrawable();
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitDrawable = (BitmapDrawable) drawable;
Bitmap bit = bitDrawable.getBitmap();
int rowBytes = bit.getRowBytes();
int height = bit.getHeight();
long memSize = rowBytes * height;
Log.d("ANDROID_LAB", "memSize =" + memSize + "B =" + formatFileSize(memSize));
}
public static String formatFileSize(long size) {
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (size >= gb) {
return String.format("%.1f GB", (float) size / gb);
} else if (size >= mb) {
float f = (float) size / mb;
return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
} else if (size >= kb) {
float f = (float) size / kb;
return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
} else
return String.format("%d B", size);
}
或者
public final int getByteCount() {
// int result permits bitmaps up to 46,340 x 46,340
return getRowBytes() * getHeight();
}