Android里面加载大图片的话很容易引起内存溢出,out of memory,因为如果你如果把一张很大的原图加载到ImageView的话,会提示
一张图片在内存中占有多大呢,Bitmap有个函数可以直接获取内存中占有的大小。我们看下Bitmap类里面
/**
* Returns the minimum number of bytes that can be used to store this bitmap's pixels.
*
* <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, the result of this method can
* no longer be used to determine memory usage of a bitmap. See {@link
* #getAllocationByteCount()}.</p>
*/
public final int getByteCount() {
if (mRecycled) {
Log.w(TAG, "Called getByteCount() on a recycle()'d bitmap! "
+ "This is undefined behavior!");
return 0;
}
// int result permits bitmaps up to 46,340 x 46,340
return getRowBytes() * getHeight();
}
其中getRowBytes()是获取一行像素的内存大小。我们可以用getByteCount来获取图片的大小。比如我们项目里放一张10M的图片,然后执行getByteCount(),然后将大小打印出来。
如果要自己手算的话,也是可以算的,不过比较麻烦:
当图片以格式ARGB_8888存储时的计算方式
占用内存=图片长*图片宽*4字节
图片长 = 图片原始长 (设备DPI/文件夹DPI)
图片宽 = 图片原始宽(设备DPI/文件夹DPI)
好了。
比如我这张图片的大小如果是9318427byte的话(暂时还想不到办法得到一张完整10兆的图片,只能近似地取了一张9M多的图片)。那么执行函数的到的大小是162739584 325479168 当前的设备dpi为420,文件夹是mdpi,也就是240.然后算一下, (420/240)* (3968*2976)* 4= 82661376 byte 。