您的位置:首页 > 其它

如何有效使用bitmap

2013-11-24 22:02 176 查看
使用bitmap容易遭遇out of memory exception,主要由以下三个原因:

每个android app分配的内存有限;

bitmap比较耗费内存,例如1300w像素图片,每个像素可能占4个字节;

有些view group例如list view,grid view中可能包含很多bitmap。

综上,使用bitmap时主要考虑节省内存,方式主要是减小bitmap的大小,因为UI上的image view往往不是太大,所以可以缩小bitmap,

(另外,当你从文件,硬盘,网络上decode图片时,不要在UI thread执行,可以放在async task中)

上一篇文章拍照的code里面其实已经包含了这部分内容。

/* Get the size of the ImageView */
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();

 //设置BitmapFactory.Option中的这个选项为true,这样在decode的时候会暂不分配内存,只会拿到原来图片的大小
bmOptions.inJustDecodeBounds = true;
//有一系列的decode方法,用来从不同的源decode出图片,decodeFile是从文件中decode出图片

BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
//根据图片大小和image view的确定缩小比例

int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}

/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;//把这个值设置为false重新decode,这样会真正分配内存
bmOptions.inSampleSize = scaleFactor;//缩小比例,如果为2,那长宽都变成原来的一半,面积是原来1/4
bmOptions.inPurgeable = true;

/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath,
bmOptions);

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: