Skip to content

Downloading custom sizes with Glide

Sam edited this page May 20, 2017 · 3 revisions

Glide V4

For information on Glide v4, see the documentation. This wiki covers Glide v3 only.


Glide's ModelLoader interface provides developers with the size of the view they are loading an image into and allows them to use that size to choose a url to download an appropriately sized version of the image.

Using appropriately sized image saves bandwidth, storage space on the device, and improves the performance of the app.

The 2014 Google I/O app team wrote a post about how they used the ModelLoader interface to adjust the size of the images they loaded on the Github page for the I/O app source.

To implement your own ModelLoader to download images over http or https, you can extend BaseGlideUrlLoader:

public interface MyDataModel {
    public String buildUrl(int width, int height);
} 

public class MyUrlLoader extends BaseGlideUrlLoader<MyDataModel> {
	@Override
	protected String getUrl(MyDataModel model, int width, int height) {
		// Construct the url for the correct size here.
        return model.buildUrl(width, height);
	}
}

You can then use your custom ModelLoader to load images, and everything else works automatically:

Glide.with(yourFragment)
    .using(new MyUrlLoader())
    .load(yourModel)
    .into(yourView);

If you want to avoid calling .using(new MyUrlLoader()) each time, you can also implement a custom ModelLoaderFactory and register it with Glide in your GlideModule.

public class MyGlideModule implements GlideModule {
    ...
    @Override
    public void registerComponents(Context context, Glide glide) {
        glide.register(MyDataModel.class, InputStream.class, 
            new MyUrlLoader.Factory());
    }
}

After registering the ModelLoaderFactory, you can skip the .using() call and just call:

Glide.with(yourFragment)
    .load(yourModel)
    .into(yourView);

For another example of how to load a variety of image sizes using a custom ModelLoader, see Glide’s Flickr sample app or Glide’s Giphy sample app.