繁体   English   中英

从服务器下载多个图像(每个> 2mb)时Android内存不足异常

[英]Android Out of memory exception while downloading multiple images(>2mb each) from server

这是我的代码,在下载多个图像时出现 outofMemory 异常。 我经历了一个重复的问题,但没有找到合适的答复。

try {
  HttpGet httpRequest = new HttpGet("http://staging.xyz.com/db/demo_img/abc.png");
  HttpClient httpclient = new DefaultHttpClient();
  HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
  HttpEntity entity = response.getEntity();
  BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity);
  InputStream is = bufferedHttpEntity.getContent();
  //Drawable d = Drawable.createFromStream(is, "");
  //or bitmap
  //photos = BitmapFactory.decodeStream(is);
  BitmapFactory.Options o = new BitmapFactory.Options();
  o.inJustDecodeBounds = true;
  BitmapFactory.decodeStream(is,null,o);
  //The new size we want to scale to
  final int REQUIRED_SIZE=70;
  //Find the correct scale value. It should be the power of 2.
  int scale=1;
  while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
   scale*=2;
  //Decode with inSampleSize
  BitmapFactory.Options o2 = new BitmapFactory.Options();
  o2.inSampleSize=scale;
  Bitmap photos= BitmapFactory.decodeStream(is, null, o2);

} catch (MalformedURLException e) {
  System.out.println("photo error1111");
  // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
  System.out.println("photo error1111");
  // TODO Auto-generated catch block
  e.printStackTrace();
}

我注意到你没有回收位图。 那会是你问题的根源吗?

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        photos.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

只需添加它即可节省您的内存

或者干脆试试这个:

BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize=2;                             CameraAndFolderActivity.myBitmap = BitmapFactory.decodeFile(info.aImagePath, options);  

使用垃圾收集器..

System.gc();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM