0

我在将 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 中执行此操作没有问题。

4

1 回答 1

2

问题就在这里

 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 的倍数的文件 - 通常情况并非如此。现在,当使用额外的尾随字节保存图像时会发生什么取决于格式和图像阅读器。在某些情况下,它可能会起作用。尽管如此,还是错了。

顺便说一句:永远不要吞下异常——即使这不是今天的问题,也可能是明天的问题,你可能会花费数小时来寻找问题。

于 2015-03-04T16:09:51.417 回答