Mike Spike Mike Spike - 4 months ago 81
Android Question

Android Glide load picture file apply overlay and set to imageview

I have image files(png/jpg). When loading to listview, some of them I need to overlay with another transparent image. I do this using something like the following:

public Bitmap applyOverlay(Context context, Bitmap sourceImage, int overlayDrawableResourceId){
Bitmap bitmap = null;
try{
int width = sourceImage.getWidth();
int height = sourceImage.getHeight();
Resources r = context.getResources();
Drawable imageAsDrawable = new BitmapDrawable(r, sourceImage);
Drawable[] layers = new Drawable[2];
layers[0] = imageAsDrawable;
layers[1] = new BitmapDrawable(r, BitmapUtils.decodeSampledBitmapFromResource(r, overlayDrawableResourceId, width, height));
LayerDrawable layerDrawable = new LayerDrawable(layers);
bitmap = BitmapUtils.drawableToBitmap(layerDrawable);
}catch (Exception ex){}
return bitmap;
}


where BitmapUtils is a custom class that implements bitmap-wise methods.


Using Universal Image Loader library for Android(UIL), this effect is achieved by writing a custom ImageDecoder and applying it to the ImageLoaderConfiguration.


The question is, how can I do this using Glide?

Thanks.

Answer

The thing that worked for me:
I used the following answer: http://stackoverflow.com/a/33709650/3106975

public void display(final Context context, String mediaPath, final ImageView imageView, final boolean doApplyOverlay){
        try{                
                Glide.with(context)
                        .load(mediaPath)
                        .asBitmap()
                        .placeholder(R.drawable.placeholder_default)
                        .error(R.drawable.error_default)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                if (doApplyOverlay) {
                                    resource = BitmapUtils.applyOverlay(context, resource, R.drawable.overlay);
                                }
                                imageView.setImageBitmap(resource);
                            }
                        });    
        }catch (Exception ex){}
    }



So, to load a bitmap and to interact with it before displaying to the user, you need to implement a custom target and do the interactions there. SimpleTarget class provided by Glide implements the Target interface and allows that kind of things. For more information, you can visit Glide's CustomTargets wiki page on github: https://github.com/bumptech/glide/wiki/Custom-targets