Retrofit 2 download image and save to folder

Zookey picture Zookey · Feb 20, 2016 · Viewed 9.1k times · Source

I need to download image from server and save it to folder, so I am using Retrofit 2.

Problem is that saved images is empty when I look for it in folder and I tried to debug and saw that Bitmap is null.

I do not get why, here is my code:

@GET("images/{userId}/{imageName}")
@Streaming
Call<ResponseBody> downloadImage(@Path("userId") String userId, @Path("imageName") String imageName);

Download image code:

 private void downloadImage(final int position) {
    String url = "htttp://myserver.com/";
        retrofitImage = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

    imageApi = retrofitImage.create(BlastApiService.class);

    String userId = feedList.get(position).getUserId();
    String fileName = feedList.get(position).getFile();

    Call<ResponseBody> imageCall = imageApi.downloadImage(userId, fileName );
    imageCall.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if(response.isSuccess()){
                String fileName = feedList.get(position).getFile();
                InputStream is = response.body().byteStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                saveImage1(bitmap, fileName);
            } else{
                try {
                    Log.d("TAG", "response error: "+response.errorBody().string().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d("TAG", "Image download error: " + t.getLocalizedMessage());
        }
    });

}

Here is method to save image.

 private void saveImage1(Bitmap imageToSave, String fileName) {
    // get the path to sdcard
    File sdcard = Environment.getExternalStorageDirectory();
    // to this path add a new directory path
    File dir = new File(sdcard.getAbsolutePath() + "/FOLDER_NAME/");
    // create this directory if not already created
    dir.mkdir();
    // create the file in which we will write the contents
    File file = new File(dir, fileName);
    try {
        FileOutputStream out = new FileOutputStream(file);
        imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        counter++;
       // if (counter < feedList.size()) {
            //downloadImage(counter);
        //} else {
            setImage();
        //}
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Answer

David picture David · Jun 17, 2017

This worked for me:

public static boolean writeResponseBody(ResponseBody body, String path) {
    try {

        File file = new File(path);

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            byte[] fileReader = new byte[4096];
            //long fileSize = body.contentLength();
            //long fileSizeDownloaded = 0;

            inputStream = body.byteStream();
            outputStream = new FileOutputStream(file);

            while (true) {
                int read = inputStream.read(fileReader);

                if (read == -1) {
                    break;
                }
                outputStream.write(fileReader, 0, read);
                //fileSizeDownloaded += read;
            }

            outputStream.flush();

            return true;
        } catch (IOException e) {
            return false;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }

            if (outputStream != null) {
                outputStream.close();
            }
        }
    } catch (IOException e) {
        return false;
    }
}

after call this method you can get image from path:

boolean result = writeResponseBody(body, path);
if(result) {
    Bitmap bitmap = BitmapFactory.decodeFile(path)
}