android下载大图片避免OOM的解决方法

android下载大图片(例如微博长图片)会出现OOM down掉问题

解决这个问题的办法是下载图片时先得到图片的宽度和高度,如果超出规定限制则对图片进行缩放

关键参数

1. BitmapFactory.Options.inJustDecodeBounds

inJustDecodeBounds:boolean类型,如果设为true,则进行辩解判断,并不申请bitmap内存

2.BitmapFactory.Options.inJustDecodeBounds.outWidth和outHeight

如果inJustDecodeBounds为true,则可得到outWidth和outHeight的值,根据这个两个值决定是否进行缩放

eg

public static Drawable loadImage(String url){
		URL m;
		InputStream is = null;
		try {
			m = new URL(url);
			is = (InputStream) m.getContent();
			BufferedInputStream bis = new BufferedInputStream(is);	
			//标记其实位置,供reset参考
			bis.mark(0);
			
			BitmapFactory.Options opts = new BitmapFactory.Options();
			//true,只是读图片大小,不申请bitmap内存
			opts.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(bis, null, opts);
			Log.v("AsyncImageLoader", "width="+opts.outWidth+"; height="+opts.outHeight);
			
			int size = (opts.outWidth * opts.outHeight);
			if( size > 1024*1024*4){
				int zoomRate = 2;
                                //zommRate缩放比,根据情况自行设定,如果为2则缩放为原来的1/2,如果为1不缩放
				if(zoomRate <= 0) zoomRate = 1;
				opts.inSampleSize = zoomRate;
				Log.v("AsyncImageLoader", "图片过大,被缩放 1/"+zoomRate);
			}
			
			//设为false,这次不是预读取图片大小,而是返回申请内存,bitmap数据
			opts.inJustDecodeBounds = false;
			//缓冲输入流定位至头部,mark()
			bis.reset();
			Bitmap bm = BitmapFactory.decodeStream(bis, null, opts);
			
                        is.close();
                        bis.close();
			return (bm == null) ? null : new BitmapDrawable(bm);
		} catch (MalformedURLException e1) {
			Log.v("AsyncImageLoader", "MalformedURLException");
			e1.printStackTrace();
		} catch (IOException e) {
			Log.v("AsyncImageLoader", "IOException");
			e.printStackTrace();
		}
		return null;
}


  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值