处理多个图像时出现内存不足错误

时间:2011-08-02 09:30:57

标签: android memory-leaks out-of-memory

  

可能重复:
  OutOfMemoryError: bitmap size exceeds VM budget :- Android

我的代码如下,捕获的图像大小约为300KB。如果imageCount = 1它正常工作,这意味着它可以处理一个没有内存异常的图像。但是当我们有多个图像时,它会产生java.lang.OutOfMemoryError:bitmap size exceeds VM budget。我认为问题是,在for loop的每次迭代之后,bitmap,byte array and string的分配空间不是免费的。我试过System.gc(),没用。我怎么能解决这个问题?

try{

                            HttpPost post = new HttpPost("http:url");
                            for( int i = 0; i <= imageCount; i++ ) {
                                String methodName = "new_receipt";
                                JSONObject json = new JSONObject();
                                Bitmap bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + File.separator +  "captured_receipt"+i+".jpg");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); //6291456 9555000
                                bm.compress(Bitmap.CompressFormat.JPEG, 10, baos); //bm is the bitmap object   
                                byte[] b = baos.toByteArray();
                                String encodedImage = Base64.encodeBytes(b);//Base64.DEFAULT               
                                json.put("Key", key);
                                json.put("image_no", i);
                                json.put("image",encodedImage);
                                methodName = "add_image";
                                List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(3);
                                nameValuePairs.add(new BasicNameValuePair("module", "expense"));
                                nameValuePairs.add(new BasicNameValuePair("method", methodName));
                                nameValuePairs.add(new BasicNameValuePair("json", json.toString()));
                                post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
                                response = client.execute(post);
                            }
                           } catch(Exception e){
                                  Log.d("MY Error",e.getMessage());
                              } 

1 个答案:

答案 0 :(得分:0)

每次发布​​到服务器后使用bm.recycle()bm=null

编辑:我认为为每个文件创建Bitmap都没用。您只需将文件读入StringBuffer并将其传递给JSONObject