Ilya Gazman
Ilya Gazman

Reputation: 32271

Glide custom URI scheme

I need to load images from my database, I store them in blobs just like android. Each image is represented by my costume URI. How can I work it out with Glide?

I want to benefit from Glide cache and fast loading.

Is there a proper way of doing this?

Upvotes: 0

Views: 384

Answers (1)

7heaven
7heaven

Reputation: 807

you can register customize ModelLoader class to Glide by calling Glide.get(context).register() method. and in your ModelLoader, you can tell Glide how to load image resources from your database by implement getResourceFetcher method and return a customize DataFetcher instance.

here's a example:

DBImageUri class:

public class DBImageUri {

private String uriString;

public DBImageUri(String uriString){
    this.uriString = uriString;
}

@Override
public String toString(){
    return uriString;
}
}

DBDataFetcher class:

public class DBDataFetcher implements DataFetcher<InputStream> {

private DBImageUri uri;
private int width;
private int height;

private InputStream stream;

public DBDataFetcher(DBImageUri uri, int width, int height){
    this.uri = uri;
    this.width = width;
    this.height = height;
}

@Override
public InputStream loadData(Priority priority){
    String uriString = this.uri.toString();

    stream = //**load image based on uri, and return InputStream for this image. this is where you do the actual image from database loading process**;

    return stream;
}

@Override
public String getId(){
    //width & height should be ignored if you return same image resources for any resolution (return uri.toString();)
    return uri.toString() + "_" + width + "_" + height;
}

@Override
public void cleanup(){
    if (stream != null) {
        try {
            stream.close();
        } catch (IOException e) {
            // Ignore
        }
    }
}

@Override
public void cancel(){

}
}

DBModelLoader class:

public class DBModelLoader implements ModelLoader<DBImageUri, InputStream> {

@Override
public DataFetcher<InputStream> getResourceFetcher(DBImageUri model, int width, int height){

    return new DBDataFetcher(model, width, height);
}

public static class Factory implements ModelLoaderFactory<DBImageUri, InputStream>{

    @Override
    public ModelLoader<DBImageUri, InputStream> build(Context context, GenericLoaderFactory factories){
        return new DBModelLoader();
    }

    @Override
    public void teardown(){

    }

}
}

and then you add ModelLoader to Glide registry by calling:

Glide.get(context).register(DBImageUri.class, InputStream.class, new DBModelLoader.Factory());

now you can load you database images:

Glide.with(context).load(new DBImageUri(/*your unique id string for database image*/)).into(imageview);

Upvotes: 1

Related Questions