如何在android上下载长度未知的图像文件
我正在尝试显示来自本地网络url的文件如何在android上下载长度未知的图像文件,android,image,http,download,inputstream,Android,Image,Http,Download,Inputstream,我正在尝试显示来自本地网络url的文件 http://192.168.1.118:1881/image.jpg 并立即在ImageView中显示它。问题是,当我打开此url的inputStream并尝试使用BitmapFactory对其进行解码时,会得到空位图。我想这是因为我从输入流获得了这个消息:libcore.net.http.UnknownLengthHttpInputStream 该图像由我无法修改的服务器应用程序支持和托管 非常感谢,我一直在努力寻找解决方案,但没有任何方法适合我尝试
http://192.168.1.118:1881/image.jpg
并立即在ImageView中显示它。问题是,当我打开此url的inputStream并尝试使用BitmapFactory对其进行解码时,会得到空位图。我想这是因为我从输入流获得了这个消息:libcore.net.http.UnknownLengthHttpInputStream
该图像由我无法修改的服务器应用程序支持和托管
非常感谢,我一直在努力寻找解决方案,但没有任何方法适合我尝试下载完整图像,然后在下载完成后显示。例如,将所有下载的字节写入数组,然后使用
BitmapFactory.decodeByteArray
。或者将图像保存到临时文件,然后使用BitmapFactory.decodeFile,然后删除该文件。将其下载到字节数组并解码字节数组:
byte[] data = read(inputStreamFromConnection);
if (data != null) {
Bitmap downloadedBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
public static byte[] read(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
try {
// Read buffer, to read a big chunk at a time.
byte[] buf = new byte[2048];
int len;
// Read until -1 is returned, i.e. stream ended.
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
} catch (IOException e) {
Log.e("Downloader", "File could not be downloaded", e);
} finally {
try {
is.close();
} catch (IOException e) {
// Input stream could not be closed.
}
}
return baos.toByteArray();
}
谢谢现在下载就可以了。我的意思是在数据数组中有很多东西。但试图通过BitmapFactory对其进行解码仍然不起作用。它返回空值:(奇怪。我现在试用了该代码,它在网络上的随机图像URL上运行得非常完美。你能将你图像的URL粘贴到浏览器中,以确保它确实显示在浏览器中吗?它可能是一个损坏的jpeg。也许可以尝试在网络上使用另一个URL?另外,确保你的
AndroidManifest.xml
中有
。