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;
}
我试图从网址中检索图片,但不管它总是返回null。在调试模式中,我观察到它在尝试input.close()时发生; 。 我怎么可能得到图像。
答案 0 :(得分:1)
这是加载位图的正确方法:
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) {
}
BTW,请参阅this post,它也可以正常工作