如何有效使用bitmap

使用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);




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值