url="http://www.nasa.gov/sites/default/files/styles/946xvariable_height/public/ladee_spin_2_in_motion_0_0.jpg?itok=yNhf69rE";
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}我试图从url中检索图片,但不管怎样,它总是返回null。在调试模式下,我观察到它在尝试input.close();时发生。我怎么可能得到图像。
发布于 2013-09-15 17:16:21
这是加载位图的正确方法:
InputStream is;
Bitmap bitmap;
is = context.getResources().openRawResource(DRAW_SOURCE);
bitmap = BitmapFactory.decodeStream(is);
try {
is.close();
is = null;
} catch (IOException e) {
}然而,正如我所看到的,你在解码之前关闭了流。
如果是,请使用其他方法:
Bitmap bitmap;
InputStream input = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(input, 8192);
ByteArrayBuffer buff = new ByteArrayBuffer(64);
int current = 0;
while ((current = bis.read()) != -1) {
buff.append((byte)current);
}
byte[] imageData = buff.toByteArray();
bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
try {
is.close();
is = null;
} catch (IOException e) {
}顺便说一句,参见this post,它也应该可以工作
https://stackoverflow.com/questions/18810728
复制相似问题