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;
- }