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