0

サーバーから Android アプリに PNG 画像をダウンロードする際に問題が発生しています。この問題は 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