Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rameshvoltella/306e48458ea24e9dfb6744c6b54cee13 to your computer and use it in GitHub Desktop.
Save rameshvoltella/306e48458ea24e9dfb6744c6b54cee13 to your computer and use it in GitHub Desktop.
Glide 3.6.0 proof of concept for loading a Bitmap as Bitmap through Glide
class BitmapBitmapResourceDecoder implements ResourceDecoder<Bitmap, Bitmap> {
private final BitmapPool pool;
public BitmapBitmapResourceDecoder(Context context) {
this(Glide.get(context).getBitmapPool());
}
public BitmapBitmapResourceDecoder(BitmapPool pool) {
this.pool = pool;
}
@Override public Resource<Bitmap> decode(Bitmap source, int width, int height) throws IOException {
return BitmapResource.obtain(source, pool);
}
@Override public String getId() { return "BitmapBitmapResourceDecoder"; }
}
GenericRequestBuilder<Bitmap, Bitmap, Bitmap, Bitmap> glide = Glide
.with(context)
.using(new PassthroughModelLoader<Bitmap, Bitmap>(), Bitmap.class)
.from(Bitmap.class)
.as(Bitmap.class)
.decoder(new BitmapBitmapResourceDecoder(context))
.cacheDecoder(new FileToStreamDecoder<Bitmap>(new StreamBitmapDecoder(context)))
.encoder(new BitmapEncoder())
// or .diskCacheStrategy(DiskCacheStrategy.NONE) instead of last 2
;
// simulate a bitmap input coming from somewhere
Bitmap bitmap = getBitmap(android.R.drawable.sym_def_app_icon);
glide
.clone() // if you use the same glide multiple times (e.g. in Adapter)
.load(bitmap)
.signature(new StringSignature("android.R.drawable.sym_def_app_icon")) // required for cache to be correct
// ... add whatever you want here (transformation, animation ...)
.into(imageView)
;
Bitmap getBitmap(@DrawableRes int id) {
Drawable drawable = getResources().getDrawable(id);
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
}
class PassthroughModelLoader<Result, Source extends Result> implements ModelLoader<Source, Result> {
@Override public DataFetcher<Result> getResourceFetcher(final Source model, int width, int height) {
return new CastingDataFetcher<Source, Result>(model); // upcasting is ok
}
/** Extremely unsafe, use with care. */
private static class CastingDataFetcher<Source, Result> implements DataFetcher<Result> {
private final Source model;
public CastingDataFetcher(Source model) {
this.model = model;
}
@SuppressWarnings("unchecked")
@Override public Result loadData(Priority priority) throws Exception {
return (Result) model;
}
@Override public void cleanup() { }
@Override public String getId() { return ""; }
@Override public void cancel() { }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment