0

更新:

经过一番搜索后,我似乎并不孤单:

http://code.google.com/p/android/issues/detail?id=6066

https://groups.google.com/forum/?fromgroups#!topic/android-beginners/dDnHEacrpCE

ATM有两种解决方案:

1.(仅在某些情况下有效)在调用静态 decodeStream() 方法之前,实现一个 Thread.sleep(300) (可能睡眠持续时间值必须更高,但 300 ms 对我有用)

2. 替换以下内容:

URL pictureurl = new URL("http://www.somewebsite.com/picture15.jpg");
URLConnection urlConn = pictureurl.openConnection();
urlConn.connect();
InputStream urlStream = urlConn.getInputStream();

使用以下内容(如 imran khan 建议的那样):

HttpGet httpRequest = new HttpGet();
httpRequest.setURI(new URI("http://www.somewebsite.com/picture15.jpg"));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();

因此,我接受 imran khan 的回答,因为它是这篇文章中所有答案中唯一有效的答案。


我的 Android 应用程序中有以下代码:

URL pictureurl = new URL("http://www.somewebsite.com/picture15.jpg");

URLConnection urlConn = pictureurl.openConnection(); // NOT NULL
urlConn.setRequestProperty("Referer", "http://www.somewebsite.com/");
urlConn.connect();
InputStream urlStream = urlConn.getInputStream(); // NOT NULL

Bitmap bm = BitmapFactory.decodeStream(urlStream);
Bitmap bm2 = Bitmap.createScaledBitmap(bm, 100, 100, true);

imageView.setImageBitmap(bm2);

方法“decodeStream()”返回null,当我使用来自某个网​​站的某个图像但当我在浏览器中加载图像时它显示得很好。我可以使用来自其他网站的其他图像,这些图像会导致方法“decodeStream()”返回预期的位图实例。

我注意到“decodeStream()”方法的方法解释中有以下文字:

如果输入流为空,或者不能用于解码位图,则函数返回空” - 我的输入流不为空

下图导致方法“decodeStream()”返回 null:

http://i45.tinypic.com/eah2d2.jpg

下图导致方法“decodeStream()”返回预期的位图实例:

https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Wiktionary_small.svg/350px-Wiktionary_small.svg.png

我使用的是安卓 1.5。

这是 Android/Java 环境中的错误还是我做错了什么?

4

2 回答 2

3

尝试以下:

HttpGet httpRequest = new HttpGet();
httpRequest.setURI(new URI("http://www.somewebsite.com/picture15.jpg"));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();
于 2012-06-27T12:30:13.003 回答
0
You need to pass BufferedInputStream.

BufferedInputStream bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );

所以你的解码流的代码将是。

InputStream urlStream = urlConn.getInputStream(); // 非空

BufferedInputStream bis = new BufferedInputStream( urlStream );
Bitmap bm = BitmapFactory.decodeStream(bis);
Bitmap bm2 = Bitmap.createScaledBitmap(bm, 100, 100, true);
于 2012-06-27T12:32:43.343 回答