Android Glide Library Tutorial With Example

If you are new developer, you should be using android official programming language i.e. Kotlin. This post is written in Java. So, if you want to learn how to use glide library in Kotlin, Click here

Android Glide Library is another popular android libraries for image downloading and caching, developed by bumptech. It is basically focused on smooth scrolling. Moreover, it is recommended by Google and google has used it in many official applications. It is a fast and efficient open source media management and image loading framework for Android that wraps media decoding, memory and disk caching and resource pooling into a simple and easy to use interface. It includes a flexible API that allows developers to plug in to almost any network stack.
Glide’s primary focus is on making scrolling any kind of a list of images as smooth and fast as possible, but Glide is also effective for almost any case where you need to fetch, resize, and display a remote image.

Android Glide Library Features

a. Animated GIF decoding : you can load GIF animation into ImageView.
b. Display Video stills
c. Supports Thumbnail
d. Transcoding
e. Supports Animations
f. Supports OkHttp and Volley library
g. Placeholder can be added before loading the original image.
h. Any custom image can be shown if error occurs while loading the original image.

Note: Glide Library requires a minimum API level of 10. It can load huge images by downsampling them.

Why do we need libraries?

Without using libraries, It’s very tough task to download and show images into any application. For example, To show images from any external urls, You would need to consider following things –
a. downloading the complete image from remote location, handle network errors if occurs while downloading.
b. Implement image caching.
c. Image transformation. You may need to transform the image at run time with handling OutOfMemoryException.

To perform all of the above task, you would need too much code. Also, It’s likely to forget some test cases that would be headache to solve.

There comes role of libraries that does the some task on behalf of you, You just need to do some initial setup and write a few lines of code. Then, you are done and can show images into your application.

Android Glide library is similar to another popular android image loading library Picasso .
a. Both are on jcenter
b. The way to load image into ImageView is quite same in both.
There are many more similarities between them But i am not going into details for the sake of this post.

Check out tutorial on picasso library to load image into ImageView.

Output

Tutorialwing - android Glide library tutorial output

Tutorialwing – android Glide library tutorial output

Video Output

Source Code

Glide Tutorial Source Code

1. Getting started

In this tutorial, We will learn how to use Glide library in android project.

1.1 Creating new project

Follow steps written below to create a new project.
a. Goto File –> New –> New Project. Then, Write application name as GlideLibraryTutorial and click next.
b. Select Minimum SDK 15 or more –> click next –> Select Empty Activity –> click next –> click finish.
If you have followed above process correctly, you will get a newly created project successfully.
You will get folder structure like below.

tutorialwing android glide porject structure

Tutorialwing- Android Glide tutorial project structure

1.2 Add Gradle into app/build.gradle file

Add gradle for Glide into app/build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'

    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:23.4.0'
}

1.3 Add internet permission into AndroidManifest.xml file

Since we are going to do network operations, we need to add internet permission in AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest package="tutorialwing.com.glidelibrarytutorial"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

1.4 Prepare layout to show output

We are going to load into ImageView using Glide Library. So, add ImageView into activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</RelativeLayout>

1.5 Add code in MainActivity to load image into ImageView

You may load image, into ImageView, present in different locations, e.g. image may be present in res/drawable folder, image may be present in certain url location etc. We can load these images as follow

1.5.1 Get the reference to ImageView

At first, get the reference to View where you want to show image. Here, we are showing image into ImageView.

//Initialize ImageView
ImageView imageView = (ImageView) findViewById(R.id.imageView);

Since you have the reference to ImageView, you can write code to load image into ImageView.

1.5.2 Loading image present in server

Get the url where image is present and show it into ImageView, You need to write the code as below.

//Loading image from url into imageView
Glide.with(this)
	.load("IMAGE URL HERE")
	.into(imageView);

For demo purposes, we are showing an image present in http://goo.gl/gEgYUd url. However, you can choose any image url of your own choice. so, MainActivity.java code will be like below.

1.5.3 MainActivity.java code

package tutorialwing.com.glidelibrarytutorial;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

public class MainActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		//Initialize ImageView
		ImageView imageView = (ImageView) findViewById(R.id.imageView);

		//Loading image from below url into imageView
		Glide.with(this)
			.load("http://goo.gl/gEgYUd")
			.into(imageView);
	}
}



2. Advance concepts in Android Glide Library

Till now, we have seen the basic concepts in android Glide Library. Now, we will see some advance concepts in Glide Library.

2.1 Loading Image from Different sources

You can load images from different sources into any View using this library.

2.1.1 Loading image from res/drawable folder

Glide.with(this)
	.load(R.drawable.IMAGE_NAME)
	.into(imageView);

2.1.2 Loading image from any server location

//Loading image from any server location into imageView
Glide.with(this)
	.load("IMAGE URL HERE")
	.into(imageView);

2.1.3 Loading image from any file location

//Loading image from any file location into imageView
Glide.with(this)
	.load(new File("..File location.."))
	.into(imageView);

2.2 Show placeholder image

Write code as below to show placeholder image while original image is being loaded.

Glide.with(this)
       .load("IMAGE URL HERE")
       .placeholder(R.drawable.PLACEHOLDER_IMAGE_NAME)
       .into(imageView);

2.3 Show error image

If you want to show image when error occurs while loading original image, you have to write it as below.

Glide.with(this)
       .load("IMAGE URL HERE")
       .error(R.drawable.ERROR_IMAGE_NAME)
       .into(imageView);

2.4 Transform image

If you want to transform image, resize it, crop it. you can do it as below.

Glide.with(this)
       .load("IMAGE URL HERE")
       .override(200, 200)
       .centerCrop()       
       .into(imageView);

Based on the options we have, We are resizing the images to 200 x 200 and center-cropping it. Finally, Our MainActivity.java code would look like below.

Final MainActivity.java code

package tutorialwing.com.glidelibrarytutorial;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

public class MainActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		//Initialize ImageView
		ImageView imageView = (ImageView) findViewById(R.id.imageView);

		//Loading image from below url into imageView
		Glide.with(this)
				.load("http://goo.gl/gEgYUd")
				.override(200, 200)
				.centerCrop()
				.into(imageView);
	}
}

Finally if you run the app, you will get output as shown above in this post.

3. Android Glide Library vs Picasso Library

You may be confused which is better Glide or Picasso. Followings are some comparisons between two libraries.

3.1 Glide and Picasso both are on jcenter.

Both libraries are on jcenter. You can import these libraries into your project as below.
Picasso

dependencies {
    compile 'com.squareup.picasso:picasso:2.5.2'
}

Glide
Glide also needs android support library v4.

dependencies {
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:23.4.0'
}

3.2 The way to load image

The way to load image into ImageView is similar in both. But Picasso accepts only Context in with() method in Picasso.with(…..).into(imageView) while Glide accepts Context, Activity and Fragment as well. Benefit of passing Activity/Fragment is that image loading would be integrated with Activity/Fragment’s lifecycle. e.g. Image loading can be paused on pause state, resume on resume state of Activity/Fragment etc.

3.3 Bitmap format

Glide’s default bitmap format is set to RGB_565 so image quality will be poorer compared with Picasso. But the advantage is that it will consume less memory. If you are ok with image quality, don’t change the bitmap format else change it to ARGB_8888 as below.

package tutorialwing.com.glidelibrarytutorial;

import android.content.Context;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.module.GlideModule;

public class GlideConfiguration implements GlideModule {

	@Override
	public void applyOptions(Context context, GlideBuilder builder) {
		// Change bitmap format to ARGB_8888
		builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
	}

	@Override
	public void registerComponents(Context context, Glide glide) {
		// register ModelLoaders here.
	}
}

Then, Add meta-tag into AndroidManifest.xml

<meta-data android:name="tutorialwing.com.glidelibrarytutorial.GlideConfiguration"
           android:value="GlideModule"/>

If you run the app, images will look better now.

3.4 Image caching

Glide creates cached images per size while Picasso saves the full image and process it. Means If you are trying to load image(500 x 500) into imageView (200 x 200). Glide will download full image, then resize it to 200 x 200, then it will cache and load into imageView while Picasso will download full image then it will cache full image then resize it to 200 x 200 and load it into imageView.
Next time when you request same image(500 x 500) to load into imageView(100 x 100) , Glide will again download the full image(500 x 500) then resize it to 100 x 100 then cache and load into imageView. Picasso, unlike Glide, picks up the cached full size image and resize and load it into imageView(100 x 100). Picasso doesn’t download same image again.

However, you can configure Glide to cache Full Size and Resized image as below.

Glide.with(this)
     .load(“IMAGE URL HERE”)
     .diskCacheStrategy(DiskCacheStrategy.ALL)
     .into(imageView);

3.5 Structure/Design

Android Glide Library is designed in such a way that it loads and shows image very fast.

Based on the above differences , you can choose any library. If you want to save more memory, you can opt for Picasso. But if you want to show images faster you need to choose Glide.

Conclusion

Android Glide Library is a simple, easy to learn and use, yet powerful android library for image downloading and caching. Neither Glide nor Picasso are perfect. Based on above comparisons, It depends upon what we want to achieve in our application.

Pro Programming Tip

Did you know now you can remotely access your programming tool kit online on citrix vdi from CloudDesktopOnline to remotely catch up with your programming work from anywhere, anytime on any device(PC/android/iOS). Learn more about Office 365 Enterprise E3 suite and SharePoint hosting by Apps4Rent

15 Comments

  1. Lupita July 6, 2016
  2. kian August 16, 2016
  3. karthik August 24, 2016
    • Tutorialwing August 25, 2016
  4. Tirth December 21, 2016
    • Rajeev kumar December 22, 2016
      • Tirth December 26, 2016
  5. Vivek Sati January 1, 2017
    • Rajeev kumar January 3, 2017
  6. lawblood1.tumblr.com April 1, 2017
  7. Joie April 9, 2017
  8. Justina April 10, 2017
  9. Bongani Sibanda January 13, 2018

Leave a Reply