0
我從互聯網下載一些圖像並將它們存儲在位圖數組中。我有小圖像沒有問題,但與更大的圖像,因爲我使用bytearray存儲下載的流,然後將其轉換爲位圖我得到java.lang.OutOfMemoryError。你可以在下面看到我的方法的代碼。從網址下載圖片時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連接?