对Bitmap的内存优化

转载自 :"http://blog.csdn.net/arui319/article/details/7953690"


看了"Android开发优化之——对Bitmap的内存优化”后总结一下防止忘了


1) 要及时回收Bitmap的内存

//首先判断bitmap是否回收
if(bitmap != null && !bitmap.isRecycled()){
// 回收并且置为null
bitmap.recycle();
bitmap = null;

}


2) 捕获异常

Bitmap bitmap = null;

try {
// 实例化Bitmap
bitmap = BitmapFactory.decodeFile(path);
} catch (OutOfMemoryError e) {
//
}
if (bitmap == null) {
// 如果实例化失败 返回默认的Bitmap对象
return defaultBitmapMap;

}


3) 缓存通用的Bitmap对象

如果不进行缓存,尽管看到的是同一张图片文件,但是使用BitmapFactory类的方法来实例化出来的Bitmap,是不同的Bitmap对象。缓存可以避免新建多个Bitmap对象,避免内存的浪费。


4) 压缩图片


4.1 对bitmap进行缩小
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2;//宽高都变成原先的一半

Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher,opts);


4.2 不实例化bitmap而获得宽高的值
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;// 设置inJustDecodeBounds为true
BitmapFactory.decodeFile(path, opts);// 使用decodeFile方法得到图片的宽和高
int width = opts.outWidth;
int height = opts.outHeight;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值