Glide加载后保存图像

时间:2016-12-31 03:39:30

标签: android android-glide

我使用Glide加载图像,如下所示:

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

并希望保存像这样加载的Bitmap:

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();
}

问题是,如果我在saveImage加载我的照片之前致电Glide,那么它就无法工作。

我该如何等待或Glide加载它?请注意,使用Glide的听众无效。

修改

我现在使用以下监听器:

 .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 个答案:

答案 0 :(得分:2)

使用侦听器,以便在提取图像并准备使用时,可以使用您的saveImage方法保存它。

这样做:

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();
      }});

在onResourceReady()回调中调用saveImage方法并使用GlideDrawable资源。我建议使用GlideDrawable而不是使用Drawing Cache获取图片。