【问题标题】:How to download image file with unknown length on android如何在android上下载长度未知的图像文件
【发布时间】:2013-06-29 15:22:19
【问题描述】:

我正在尝试显示来自本地网络 url 的文件

http://192.168.1.118:1881/image.jpg

并在 ImageView 中立即显示。问题是,当我为这个 url 打开 inputStream 并尝试使用 BitmapFactory 对其进行解码时,我得到空位图。我想那是因为我从输入流中得到这条消息:libcore.net.http.UnknownLengthHttpInputStream。

该图像由我无法修改的服务器应用程序支持和托管。

非常感谢,我已经努力寻找解决方案,但对我没有任何帮助

【问题讨论】:

    标签: android image http download inputstream


    【解决方案1】:

    将其下载到字节数组并解码字节数组:

    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 对其进行解码仍然不起作用。它返回 null :(
    • 奇怪。我现在尝试了代码,它在网络上的随机图像 URL 上完美运行。您能否将图像的 URL 粘贴到浏览器中,以确保它实际显示在浏览器中?它可能是损坏的 jpeg。也许尝试使用网络上的另一个 URL?此外,请确保您的AndroidManifest.xml 中有<uses-permission android:name="android.permission.INTERNET" />
    【解决方案2】:

    尝试下载完整的图像,然后在下载完成后显示它。例如,将all 下载的字节写入数组,然后使用BitmapFactory.decodeByteArray。或者将图像保存到一个临时文件,然后使用BitmapFactory.decodeFile,然后删除该文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-23
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多