我有一个简单的问题:虽然我正确使用了 sampleSize,但我的代码甚至没有到达BitmapFactory
代码,因为DefaultHttpClient
已经抛出异常。
这是我的代码:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(mSongInfo.imageLarge);
HttpResponse response = client.execute(request);
int sampleSize = 1;
while (response.getEntity().getContentLength() / sampleSize
/ sampleSize > 100 * 1024) {
sampleSize *= 2;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
final Bitmap bitmap = BitmapFactory.decodeStream(response
.getEntity().getContent(), null, options);
这是一个例外:
0 java.lang.OutOfMemoryError: (Heap Size=11463KB, Allocated=7623KB, Bitmap Size=9382KB)
1 at org.apache.http.util.ByteArrayBuffer.<init>(ByteArrayBuffer.java:53)
2 at org.apache.http.impl.io.AbstractSessionInputBuffer.init(AbstractSessionInputBuffer.java:82)
3 at org.apache.http.impl.io.SocketInputBuffer.<init>(SocketInputBuffer.java:98)
4 at org.apache.http.impl.SocketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:83)
5 at org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:170)
6 at org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:106)
7 at org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:129)
8 at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:173)
9 at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10 at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11 at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
12 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
13 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
14 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
15 at de.goddchen.android.easysongfinder.fragments.SongFragment$1.run(SongFragment.java:79)
16 at java.lang.Thread.run(Thread.java:1027)
如您所见,代码甚至没有到达我检查图像大小(内容长度)并计算适当样本大小的部分。
我不知道简单的调用DefaultHttpClient.execute(...)
已经将完整的内容加载到内存中。
难道我做错了什么?首先检索内容长度然后开始读取内容的正确方法是InputStream
什么?
编辑
为了避免显示如何从 URL 加载图像的常见答案:我已经知道如何做到这一点,我也发布了上面的代码,那么你为什么要继续参考教程呢?我明确地非常清楚这个问题:为什么HttpClient.execute(...)
已经获取了整个内容并将其存储在内存中而不是为InputStream
我提供一个正确的?请不要发布任何关于如何Bitmap
从 URL 加载的初学者教程...