0

I'm using BitmapFactory.decodeStream() to download images on a background thread.
Here is the code:

URL url = new URL("https://....");
final Bitmap image = BitmapFactory.decodeStream(myUrl.openConnection().getInputStream()); 
saveImageToExternal("myImage", image, getApplicationContext());

After downloading the image I save it using the function below:

public void saveImageToExternal(String imgName, Bitmap bm, Context context) throws IOException {
    File path =new File(getFilesDir(),"ImagesFolder");
    File imageFile = new File(path, imgName+".png");
    FileOutputStream out = new FileOutputStream(imageFile);
    try{
        bm.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();
        MediaScannerConnection.scanFile(context,new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
            Log.i("ExternalStorage", "Scanned " + path + ":");
            Log.i("ExternalStorage", "-> uri=" + uri);
            }
        });
    } catch(Exception e) {
    throw new IOException();
    }
}

Problem arises if the user interrupts that process by terminating the app or by a sudden internet connection loss. What happens is that some of the images are partially decoded or downloaded.
The following code returns true when checking if the image exits.

File path =new File(getFilesDir(),"ImagesFolder");
File imageFile = new File(path, "myImage.png");
if(imageFile.exists()){
    return true;
}

The following images will show how they really appear in an ImageView:
Expected result: Expected result
Real result if interrupted: Real result
Note that both images have the same size.

The question: is there a way to check if the decoding process did finish before the interruption happens or if the image is fully downloaded?

  • Perhaps you would be better served by using something better than using `decodeStream()` for your download process. For example, you might download the image [using OkHttp](https://stackoverflow.com/a/29012988/115145). – CommonsWare May 18 '20 at 14:41
  • `I'm using BitmapFactory.decodeStream() to download images`. That is a pretty bad approach as why would you convert to bitmap first and then save to file? Better just read the bytes from the input stream and then write them to a file output stream. – blackapps May 19 '20 at 07:16

0 Answers0