从网址下载图像时Bytearray java.lang.OutOfMemoryError

时间:2012-08-08 08:01:28

标签: android memory bitmap download

我正在从互联网上下载一些图像并将它们存储在位图数组中。我没有小图像的问题,但由于我使用bytearray存储下载的流,然后将其转换为位图,我得到了java.lang.OutOfMemoryError。您可以在下面看到我方法的代码。

public static Bitmap downloadBitmap(String url) /*throws IOException,ClientProtocolException*/{
    Bitmap bitmap = null;
    HttpParams param=new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(param, timeoutConnection);

 // Set the default socket timeout (SO_TIMEOUT) 
 // in milliseconds which is the timeout for waiting for data.
 int timeoutSocket = 5000;
 HttpConnectionParams.setSoTimeout(param, timeoutSocket);

    HttpUriRequest request=new HttpGet(url.toString());
    HttpClient httpClient=new DefaultHttpClient(param);
    try {
            HttpResponse response=httpClient.execute(request);

            StatusLine statusLine=response.getStatusLine();
            int statusCode=statusLine.getStatusCode();
            if (statusCode==200) {
                HttpEntity entity=response.getEntity();
                byte[] bytes=EntityUtils.toByteArray(entity);
                bitmap=BitmapFactory.decodeByteArray(bytes,0,bytes.length);

                //the line below adjusts the width if I set the height to 100px
                int width=(bitmap.getWidth()*100)/bitmap.getHeight();

                 bitmap=Bitmap.createScaledBitmap(BitmapFactory.decodeByteArray(bytes,0,bytes.length), width, 100, false);

            }
    }
    catch (ClientProtocolException e) {
        Log.e("ReadFeed", "HTTP Error", e);
        return null;
    }
    catch (IOException e) {
        Log.e("ReadFeed", "Connection Error", e);
        return null;
    }
    catch (java.lang.OutOfMemoryError e) {
        e.printStackTrace();
    }
    finally
    {
    httpClient.getConnectionManager().shutdown();
    }
    System.out.println("resized height="+bitmap.getHeight()+"  resized width="+bitmap.getWidth());

    return bitmap;

}

是否有更有效的方法来存储我的字节流或更好的方法来处理我的http连接?

1 个答案:

答案 0 :(得分:0)

如何直接使用BitmapFactory.decodeStream(),而不是在字节数组中加载响应然后解码它?这应该可以节省一些内存。