【问题标题】:Trouble downloading PNG images in Android在 Android 中下载 PNG 图像时遇到问题
【发布时间】:2015-05-05 01:49:35
【问题描述】:

我在将 PNG 图像从我的服务器下载到我的 Android 应用程序时遇到问题。该问题特定于 PNG 图像(JPG 工作正常),问题在于下载的文件是损坏的图像。我将在下面详细解释。

场景

我需要从我的服务器下载 JPG 和 PNG 图像,并将它们显示给 Android 应用程序的用户。

问题

JPG 图像可以毫无问题地下载。但下载的 PNG 文件已损坏。我已经在我的服务器上仔细检查了图像的来源,它们是正确的。它只有下载的 PNG 文件已损坏。所以,问题可能在于我在 Android 中下载它们的方式。

代码示例

URL imageURL;
File imageFile = null;
InputStream is = null;
FileOutputStream fos = null;
byte[] b = new byte[1024];

try {
    // get the input stream and pass to file output stream
    imageURL = new URL(image.getServerPath());
    imageFile = new File(context.getExternalFilesDir(null), image.getLocalPath());
    fos = new FileOutputStream(imageFile);

    // get the input stream and pass to file output stream
    is = imageURL.openConnection().getInputStream();
    // also tried but gave same results :
    // is = imageURL.openStream();

    while(is.read(b) != -1)
        fos.write(b);

} catch (FileNotFoundException e) {
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
    // close the streams
    try {
        if(fos != null)
            fos.close();
        if(is != null)
            is.close();
    } catch(IOException e){
    }
}

任何关于我如何解决这个问题的建议,将不胜感激。

注意

由于这是在服务中发生的,因此在 AsyncTask 中执行此操作没有问题。

【问题讨论】:

  • 您应该打印Exceptions 以进一步了解那里发生的问题。
  • 在警告级别重新检查您的 logcat 并在此处发布日志
  • 我认为问题。是字节的 bcoz 你只是用它来检查它..希望它有效
  • @maven:异常中没有问题。下载文件时没有异常。
  • @Ram: 也没有 logcat 警告

标签: android png imagedownload


【解决方案1】:

问题来了

 while(is.read(b) != -1)
        fos.write(b);

这是错误的,因为在每次迭代中,它都会将完整的缓冲区(1024 字节)写入文件。但是之前的read 读取的字节数可能少于(几乎可以肯定在最后一个循环中,除非图像长度恰好是 1024 的倍数)。您应该检查每次读取了多少字节,然后写入该字节数。

 int bytesRead;
 while( (bytesRead = is.read(b)) != -1)
        fos.write(b,0,bytesRead );

您的错误使您始终编写大小为 1024 的倍数的文件 - 通常情况并非如此。现在,当使用额外的尾随字节保存图像时会发生什么取决于格式和图像阅读器。在某些情况下,它可能会起作用。不过还是错了。

顺便说一句:永远不要接受异常 - 即使这不是今天的问题,也可能是明天的问题,您可能会花费数小时来发现问题。

【讨论】:

  • 谢谢!这解决了问题!很抱歉耽搁了回来检查这里的东西,因为我遇到了一些事情!
猜你喜欢
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多