インターネットからいくつかの画像をダウンロードして、ビットマップ配列に保存しています。小さな画像では問題ありませんが、ダウンロードしたストリームをビットマップに変換する前に 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 接続を処理するより良い方法はありますか?