Save image once Glide has loaded it

8.5k Views Asked by At

I load images using Glide like such:

Glide.with(getContext()).load(apdInfo.url)
         .thumbnail(0.5f)
         .crossFade()
         .diskCacheStrategy(DiskCacheStrategy.ALL)
         .into(apd_image);

And wish to save the Bitmap loaded like such:

private void saveImage() {
    final ImageView apd_image = (ImageView) view.findViewById(R.id.apd_image);
    final InternalFileHandler IFH = new InternalFileHandler(getContext());

    apd_image.setDrawingCacheEnabled(true);
    apd_image.buildDrawingCache(true);
    Bitmap bitmap = apd_image.getDrawingCache();

    // Simply saves the bitmap in the filesystem
    IFH.savePicture("APD", bitmap, getContext());
    apd_image.destroyDrawingCache();
}

The issue is that if I call saveImage before Glide has loaded my picture, it won't work.

How may I wait or Glide to load it? Please note that using Glide's listeners did not work.

EDIT:

I now use the following listeners:

 .listener(new RequestListener<String, GlideDrawable>() {
                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                    //handle the exception.
                    return true;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    // onResourceReady is called twice for some reason, this is my work around for now
                    if (first) {
                        GlideBitmapDrawable glideBitmapDrawable = (GlideBitmapDrawable) resource;
                        // Convert to Bitmap
                        Bitmap bm = glideBitmapDrawable.getBitmap();
                        saveImage(bm);
                        first = false;
                    } else {
                        first = true;
                    }
                    return true;
                }
            })
1

There are 1 best solutions below

6
On BEST ANSWER

Use the listener so that when the image is fetched and ready to be used, you can save it using the saveImage method of yours.

Do this:

Glide.with(getContext()).load(apdInfo.url)
     .thumbnail(0.5f)
     .crossFade()
     .diskCacheStrategy(DiskCacheStrategy.ALL)
     .into(new SimpleTarget<GlideDrawable>() {
                @Override
                public void onResourceReady(GlideDrawable glideDrawable, GlideAnimation<? super GlideDrawable> glideAnimation) {
                    apd_image.setImageDrawable(glideDrawable);
                    apd_image.setDrawingCacheEnabled(true);
                    saveImage();
      }});

Call the saveImage method inside onResourceReady() callback and use the GlideDrawable resource. I would suggest using the GlideDrawable rather than getting the image using Drawing Cache.