coil image loader

Using Coil image loader for Android

COIL Image loader for Android is a relatively new library for loading images. It’s acronym is COroutine Image Loader. Let us look into how we can implement it in a new project.

Introduction

Before we start using Coil image loader in Android, let’s first understand the benefits of using it. Here are some advantages of using coil in Android:

  • Coil is a library that prioritizes Kotlin and takes advantage of many modern optimized libraries such as OkHttp, Okio, and Coroutines.
  • Coil works quickly because it uses various techniques like memory and disk caching, image down sampling, and automatic pausing and cancellation of image URL requests.
  • Coil is incredibly lightweight because it only includes around 2000 methods in the DEX.
  • It is effortless and uncomplicated to use.

I hope the information provided has helped you understand the benefits of using Coil. Now, let’s start the tutorial on how to use it.

Before we begin

Before we start, there are some fundamental things that we need to address. And the things are:

  • You need some familiarity with Kotlin and Android Studio
  • And lastly some patience and willingness to debug

Step #1: Prepare XML layout

The first step is to set up our layout. Here’s an uncomplicated example of a layout that only includes an ImageView.

Remember that the ID of this view is “imageView”. We will use this later on when we load the image.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>Code language: HTML, XML (xml)

Step #2: Add dependency in build.gradle

The next step in using Coil image loader is to add it to our project. To do this, we need to include the following line in app > build.gradle.

implementation("io.coil-kt:coil:2.3.0")
// replace number with latest version if available, but lookout for breaking API changesCode language: Groovy (groovy)

Step #3: Loading image into ImageView

After successfully integrating a new component into our project, we must now employ it to retrieve an image from a specified web address. To demonstrate this, I have selected a random image from unsplash.

And for loading the image we can utilize the ImageView extension function provided by the coil library.

// call this method from your related fragment/activity
private fun loadImageFromUrl() {
    val url ="https://images.unsplash.com/photo-1581088547417-790ffe02b79d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=765&q=100"
    val img: ImageView = findViewById(R.id.imageView)
    img.load(url)
}Code language: Kotlin (kotlin)

The piece of text above shows how to use the Coil image loader library for Android to load an image from a given web address.

Now let us look into some optional features of Coil image loader.

Step #4: Using Placeholders and Error Image

We have the option to include a temporary image that will be displayed while the main image is still loading. Additionally, we can also choose to display another image if the main image fails to load.

Let us look at the code below.

private fun loadImageFromUrl() {
    val url ="https://images.unsplash.com/photo-1581088547417-790ffe02b79d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=765&q=100"
    val img: ImageView = findViewById(R.id.imageView)
    img.load(url) {
        // placeholder shown while loading image
        placeholder(R.drawable.placeholder_image)
        // image to be shown when image loading fails
        error(R.drawable.error_image)
    }
}Code language: Kotlin (kotlin)

Step #5: Using image transformations

We can also modify the image by applying transformations like cropping or rounding to it. Take a look at code below on how we utilized the method available in coil image library.

private fun loadImageFromUrl() {
    val url ="https://images.unsplash.com/photo-1581088547417-790ffe02b79d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=765&q=100"
    val img: ImageView = findViewById(R.id.imageView)
    img.load(url) {
        // if we want circle crop
        transformations(CircleCropTransformation())
        // if we want rounded corners
        transformations(RoundedCornersTransformation())
    }
}Code language: Kotlin (kotlin)

In the code above if we want circular shape of image we can use transformations(CircleCropTransformation()).

And if we want rounded corners we can use transformations(RoundedCornersTransformation()) function.

Step #6: Adding custom headers

We can also add custom headers to the image request if we want. Let us see how can we achieve that.

private fun loadImageFromUrl() {
    val url ="https://images.unsplash.com/photo-1581088547417-790ffe02b79d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=765&q=100"
    val img: ImageView = findViewById(R.id.imageView)
    img.load(url) {
        // add your headers like below
        addHeader("header1", "value1")
    }
}Code language: Kotlin (kotlin)

In the code above we can see how we can add our own headers with each image request.

Step #7: Modifying request options

We can also modify options such as network caching, disk caching, memory caching etc. In the code below we have covered multiple cache types.

private fun loadImageFromUrl() {
    val url ="https://images.unsplash.com/photo-1581088547417-790ffe02b79d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=765&q=100"
    val img: ImageView = findViewById(R.id.imageView)
    img.load(url) {
        // enable network caching
        networkCachePolicy(CachePolicy.ENABLED)
        // enable caching on disk
        diskCachePolicy(CachePolicy.ENABLED)
        // enable memory caching
        memoryCachePolicy(CachePolicy.ENABLED)
    }
}Code language: Kotlin (kotlin)

In the code above we have enabled all the cache: memory, network and disk. You can change this behavior as per your own requirement.

With this we have come to an end of using coil image loader in our application.

Keep learning, keep progressing.

You might also like:

Android Text to Speech (TTS): A simple guide

Android Keystore: Store Sensitive Data in Android

Android Fingerprint Authentication Tutorial: How to Guide

Constructor Overloading in Java | with Examples

Related Posts