处理大图片(1)

来源:互联网 发布:2k17樱木花道脸部数据 编辑:程序博客网 时间:2024/04/20 07:08

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

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

关键参数

1. BitmapFactory.Options.inJustDecodeBounds

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

2.BitmapFactory.Options.inJustDecodeBounds.outWidth和outHeight

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

eg

[html] view plaincopy
  1. public static Drawable loadImage(String url){  
  2.         URL m;  
  3.         InputStream is = null;  
  4.         try {  
  5.             m = new URL(url);  
  6.             is = (InputStream) m.getContent();  
  7.             BufferedInputStream bis = new BufferedInputStream(is);    
  8.             //标记其实位置,供reset参考  
  9.             bis.mark(0);  
  10.               
  11.             BitmapFactory.Options opts = new BitmapFactory.Options();  
  12.             //true,只是读图片大小,不申请bitmap内存  
  13.             opts.inJustDecodeBounds = true;  
  14.             BitmapFactory.decodeStream(bis, null, opts);  
  15.             Log.v("AsyncImageLoader", "width="+opts.outWidth+"height="+opts.outHeight);  
  16.               
  17.             int size = (opts.outWidth * opts.outHeight);  
  18.             if( size > 1024*1024*4){  
  19.                 int zoomRate = 2;  
  20.                                 //zommRate缩放比,根据情况自行设定,如果为2则缩放为原来的1/2,如果为1不缩放  
  21.                 if(zoomRate <= 0) zoomRate = 1;  
  22.                 opts.inSampleSize = zoomRate;  
  23.                 Log.v("AsyncImageLoader", "图片过大,被缩放 1/"+zoomRate);  
  24.             }  
  25.               
  26.             //设为false,这次不是预读取图片大小,而是返回申请内存,bitmap数据  
  27.             opts.inJustDecodeBounds = false;  
  28.             //缓冲输入流定位至头部,mark()  
  29.             bis.reset();  
  30.             Bitmap bm = BitmapFactory.decodeStream(bis, null, opts);  
  31.               
  32.                         is.close();  
  33.                         bis.close();  
  34.             return (bm == null) ? null : new BitmapDrawable(bm);  
  35.         } catch (MalformedURLException e1) {  
  36.             Log.v("AsyncImageLoader", "MalformedURLException");  
  37.             e1.printStackTrace();  
  38.         } catch (IOException e) {  
  39.             Log.v("AsyncImageLoader", "IOException");  
  40.             e.printStackTrace();  
  41.         }  
  42.         return null;  

0 0
原创粉丝点击