0

我正在从互联网上下载一些图像并将它们存储在位图数组中。我对小图像没有问题,但对大图像没有问题,因为我使用字节数组来存储下载的流,然后再将其转换为位图我得到 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 连接?

4

1 回答 1

0

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

于 2012-08-08T14:12:06.530 回答