Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 104 ยท Networking

Loading Images with Coil

Load remote images in Jetpack Compose with Coil: AsyncImage, placeholders, memory and disk caches, sizing, transformations and the memory pitfalls to avoid.

Images are the heaviest data most apps show. A single photo from a phone camera can be 4000 by 3000 pixels, and once decoded into memory it takes about 46 MB (48 million bytes), no matter how small the file on the server was. A list with a hundred of them can crash the app with an OutOfMemoryError. Loading an image well means downloading it off the main thread, decoding it at the size you actually need, caching it, showing something useful while it loads, and cancelling the work when the user scrolls away.

You do not write that yourself. Coil (Coroutine Image Loader) is a Kotlin-first image library that does all of it and has a Compose component, AsyncImage. This lesson shows how to use it, how its caches work, and how to avoid the common memory mistakes. As in the rest of this track, the real Coil and Compose code is read-only because the site has no emulator. The TryIts are plain Kotlin stand-ins on Piston that simulate the cache and the memory arithmetic. Related lessons: Text, Images and Icons for local images, and Networking with Retrofit and OkHttp for how data gets to the device.

Setup and the simplest call

Coil is a library, so you add it in Gradle (see Gradle for Android) together with its OkHttp network module, and the app needs the INTERNET permission in the manifest, which is a normal permission and needs no prompt.

Kotlin
// read-only: app/build.gradle.kts (check the Coil releases page for current versions)
dependencies {
    implementation("io.coil-kt.coil3:coil-compose:<version>")
    implementation("io.coil-kt.coil3:coil-network-okhttp:<version>")
}
XML
<!-- read-only: AndroidManifest.xml -->
<uses-permission android:name="android.permission.INTERNET" />

Then show an image from a URL in one line:

Kotlin
// read-only
AsyncImage(
    model = "https://example.com/photos/lake.jpg",
    contentDescription = "A lake at sunrise",
    modifier = Modifier.size(160.dp),
    contentScale = ContentScale.Crop,
)

model can be a URL string, a Uri, a File, a drawable resource ID or an ImageRequest. contentDescription is required: pass a real description for meaningful images, and null for purely decorative ones so TalkBack skips them. contentScale works as in a normal Image: Crop fills the box and cuts the overflow, Fit shows everything with spare space.

AsyncImage figures out how big the image will be drawn from the constraints it receives, loads exactly that size, and starts the request when the composable enters the composition. When it leaves the composition (for example a LazyColumn item scrolls far away), the request is cancelled. That is why you should always give it a size, either through the modifier or the parent layout.

Placeholders, errors and fallbacks

A remote image is in one of four states, and you can give each its own look:

Kotlin
// read-only
AsyncImage(
    model = ImageRequest.Builder(LocalContext.current)
        .data(user.avatarUrl)          // may be null
        .crossfade(true)
        .build(),
    contentDescription = "Avatar of ${user.name}",
    placeholder = painterResource(R.drawable.avatar_placeholder),   // while loading
    error = painterResource(R.drawable.avatar_error),               // request failed
    fallback = painterResource(R.drawable.avatar_default),          // data was null
    modifier = Modifier.size(48.dp).clip(CircleShape),
    contentScale = ContentScale.Crop,
)
stateDiagram-v2
    [*] --> Loading: model set
    Loading --> Success: decoded
    Loading --> Error: network or decode failure
    [*] --> Fallback: model is null
    Success --> [*]

placeholder is shown in Loading, error in Error and fallback when the model is null.

Placeholders keep layout stable: the list does not jump when images arrive. For more control (for example a spinner while loading and a retry button on error) use SubcomposeAsyncImage, which gives you the state in a lambda, or rememberAsyncImagePainter when you need a Painter. Prefer the simple AsyncImage unless you need that control, because the subcompose version is slower inside long lists.

How the caches work

Coil keeps two caches by default, and checks them in order:

  1. Memory cache: decoded bitmaps in RAM, with a size limit (a fraction of the available memory). A hit is instant and gives you the ready-to-draw bitmap.
  2. Disk cache: the downloaded files on storage, with its own size limit. A hit skips the network, but the image still has to be decoded.
  3. Network: only when both miss. The result goes into both caches.

The caches store images under a key. The key includes the data (the URL) and the size and transformations of the request. So the same URL shown at 48 dp and at 300 dp is two different entries in the memory cache. The disk cache stores the original download, so the second size does not hit the network again.

Both memory and disk caches evict entries when they are full, using a least recently used (LRU) rule: when there is no room for a new entry, throw away the one that has not been touched for the longest time. The first TryIt simulates this with a LinkedHashMap in access order, which is also what android.util.LruCache is built on.

Kotlin An LRU image cache simulator (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Follow the log. After a.jpg is touched again, b.jpg is the least recently used entry, so it is the one evicted when d.jpg arrives, not the oldest-loaded a.jpg. And the small version of a.jpg costs a separate (and much smaller) entry.

You can tune the caches when you create a custom ImageLoader (usually once, in your Application class or through your DI container; see Dependency Injection Concepts):

Kotlin
// read-only
ImageLoader.Builder(context)
    .memoryCache { MemoryCache.Builder().maxSizePercent(context, 0.20).build() }
    .diskCache {
        DiskCache.Builder()
            .directory(context.cacheDir.resolve("image_cache"))
            .maxSizeBytes(100L * 1024 * 1024)
            .build()
    }
    .build()

The disk cache lives in the app's cache directory, which Android may clear when the device is low on space (see Files, Scoped Storage and Media). By default Coil also respects the server's HTTP cache headers (Cache-Control, ETag), so the server decides how long an image stays fresh.

Sizing: the biggest lever on memory

A bitmap in memory costs width times height times bytes per pixel, and with the default ARGB_8888 format that is 4 bytes per pixel. The file size (a 400 KB JPEG) tells you nothing about this: compression only applies on disk.

Coil avoids the problem by decoding at the target size: if the image is drawn into a 360 by 270 pixel box, it asks the decoder to downsample, which makes the decoded bitmap small and fast. Decoders downsample by integer power-of-two factors (1, 2, 4, 8, ...) and then scale the rest. The second TryIt works out the numbers for a list of photos.

Kotlin Why sizing matters: bitmap memory (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The sized version is about 64 times smaller than the full decode, and that is the whole point. When a size is unknown (for example, the image is inside a layout with wrapContentSize()), Coil cannot downsample, and it may load the original size. So give images constraints.

If you ever need a specific size, you can set it on the request:

Kotlin
// read-only
ImageRequest.Builder(context)
    .data(url)
    .size(width = 480, height = 480)       // or Size.ORIGINAL to opt out
    .build()

Transformations and options

Coil can modify an image while loading, such as CircleCropTransformation(), RoundedCornersTransformation(radius) or a blur. A few points keep that cheap:

  • In Compose, prefer modifiers and shapes: Modifier.clip(CircleShape) rounds the corners at draw time and costs nothing extra in the cache. Reserve transformations for changes to the pixels themselves.
  • A transformation becomes part of the cache key, so each combination is its own memory entry.
  • You can read the loaded image as a Bitmap through the request listeners, but avoid doing so when AsyncImage already draws it for you.

Other useful request options: crossfade(true) for a gentle fade-in, memoryCachePolicy(CachePolicy.DISABLED) for an image that must never be cached (a sensitive one), and diskCachePolicy(...) likewise. Add authentication headers through your OkHttp client when the images need a token.

Memory pitfalls

  • Loading originals into thumbnails. Give every AsyncImage a size. In a LazyColumn, a fixed Modifier.size or aspectRatio works well.
  • Holding bitmaps in ViewModels or state. A Bitmap in a StateFlow survives rotation and sits in memory for as long as the ViewModel lives. Keep URLs in state and let the composable load the pixels.
  • One ImageLoader per screen. Each loader has its own caches, so nothing is shared. Use a single loader for the app.
  • Giant GIFs and animated formats as list items, which decode many frames.
  • Using a contentDescription of "image". It is noise to TalkBack users. Describe the content or pass null for decoration.
  • Forgetting that Compose Preview cannot load the network. Use a placeholder or a local resource in previews.

Coil, Glide and Picasso compared

Coil is not the only image library you will meet. Glide and Picasso are older, and a large share of existing apps (and many job interviews) use them. All three do the same core job: download or read off the main thread, decode at the size needed, cache in memory and on disk, and cancel work that is no longer wanted. They differ in language, defaults and how well they fit Compose.

Glide in a minute

Glide (by Bump Technologies, now maintained by Google engineers) is the long-time default for View-based apps. Its API is a fluent chain, and in Views you load into an ImageView:

Kotlin
// read-only example: Glide with Views
Glide.with(imageView)                      // ties the request to the view's lifecycle
    .load("https://example.com/photos/lake.jpg")
    .placeholder(R.drawable.placeholder)
    .error(R.drawable.broken)
    .centerCrop()
    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
    .into(imageView)

Glide.with(...) accepts an Activity, Fragment or View, and Glide pauses and cancels requests along with that component's lifecycle. Glide also pools bitmaps to reduce garbage collection, which made it very smooth in long scrolling lists before Compose existed.

In Compose, the official integration is a separate artifact (com.github.bumptech.glide:compose), still marked experimental at the time of writing, which gives you a GlideImage composable:

Kotlin
// read-only example: Glide with Compose (experimental API)
@OptIn(ExperimentalGlideComposeApi::class)
@Composable
fun Photo(url: String) {
    GlideImage(
        model = url,
        contentDescription = "A lake at sunrise",
        modifier = Modifier.size(160.dp),
        contentScale = ContentScale.Crop,
    )
}

Picasso in a minute

Picasso (by Square, the makers of OkHttp) is the smallest of the three and has the simplest API: Picasso.get().load(url).into(imageView). It has no first-party Compose component and is now in maintenance mode, so for a new Compose app it is rarely the right pick. You will still find it in older codebases, where it works fine.

What actually differs

Question Coil 3 Glide Picasso
Language and concurrency Kotlin, coroutines Java, own thread pools Java, executors
Compose First-class AsyncImage Separate, experimental artifact None from the library
Kotlin Multiplatform Yes (Android, iOS, desktop, web) No No
Disk cache Yes, keyed by URL Yes, can store original and resized versions Relies on the OkHttp HTTP cache
Bitmap pooling No (lets the GC work) Yes No
Size Smallest footprint of the active libraries Largest Small
Animated GIF and WebP Via an extra module Built in Not supported out of the box

The caching difference matters most. Coil caches the decoded image in memory and the downloaded bytes on disk (through OkHttp's cache semantics). Glide can cache both the original and each resized and transformed variant on disk, which makes later loads of the same size very quick but uses more storage. Picasso has a memory cache of its own and delegates disk caching to OkHttp, so its behavior follows your HTTP cache headers. In every library the memory cache key includes the size and any transformations, which is why giant originals in thumbnails are expensive whichever you choose.

How to choose

  • New Compose app: use Coil. It is a first-party fit for Compose, shares your Kotlin coroutines and works on other platforms.
  • Existing View-based app that already uses Glide: keep Glide. It is mature, and rewriting image loading brings little benefit.
  • Heavy GIF or animated WebP use, or a need for bitmap pooling in Views: Glide has the most built-in support.
  • A tiny app on an older codebase using Picasso: leave it unless you are touching that code anyway.

Never mix two libraries on the same screen without a reason: each has its own caches, so the same image is downloaded and held in memory twice.

Migrating

Moving from Glide or Picasso to Coil is mostly mechanical, and you can do it screen by screen, because the libraries do not conflict.

  1. Add the Coil dependencies (see Setup above) and create one app-wide ImageLoader.
  2. In Compose screens, replace GlideImage(model = url) with AsyncImage(model = url, ...). The model, contentDescription and contentScale parameters have the same meaning.
  3. In View screens, replace Glide.with(view).load(url).into(view) with imageView.load(url) (the coil3.load extension) and port placeholder and error to the lambda.
  4. Port custom transformations: Glide's Transformation becomes Coil's Transformation (or, better, a Compose modifier or shape).
  5. Remove the old library and its @GlideModule and proguard rules once nothing uses it.

The stand-in below models what the three libraries disagree on: what each one stores on disk. It loads the same photo at two sizes and counts network downloads, so you can see why a variant cache trades storage for speed.

Kotlin Disk cache strategies compared (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both strategies download once. The variant cache skips the second decode of the thumbnail but stores three files instead of one. Neither is better in general: it is a trade between CPU time and storage.

Fresco and other legacy loaders

Besides Coil, Glide and Picasso, older projects use two more libraries:

  • Fresco (from Facebook) shows images through its own view, SimpleDraweeView, which supports progressive JPEG loading, rounded corners, placeholder and failure images and animated GIF/WebP. Its distinguishing idea is that decoded bitmaps live in native memory (ashmem on old devices) rather than the Java heap, which mattered on devices with a small heap. The setup is Fresco.initialize(this) in the Application class, then draweeView.setImageURI(url) in code or fresco:placeholderImage in XML. It is a bigger dependency than the others and needs its own view class, so you cannot use it with a plain ImageView.
  • Universal Image Loader was the standard before Picasso and Glide. It has been unmaintained for years; migrate any code that still calls ImageLoader.getInstance().

For new code, use Coil (Kotlin and Compose) or Glide (large View-based apps): both load off the main thread, cache in memory and on disk, and downsample to the target size, as described above.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A 4000 x 3000 photo is decoded into a bitmap at full size with 4 bytes per pixel. Roughly how much memory does it use?

    Memory is width times height times bytes per pixel: 4000 x 3000 x 4 is 48,000,000 bytes. File compression does not apply to decoded bitmaps.
  2. 2. In what order does Coil look for an image?

    The memory cache gives a ready bitmap instantly, the disk cache saves the download, and the network is the last resort. A fetched image is stored in both caches.
  3. 3. Why should AsyncImage always have a size constraint?

    Coil decodes at the size the image will be drawn. An unconstrained image gives it no target, so memory use can balloon.
  4. 4. When a memory cache is full, which entry does an LRU policy evict?

    LRU means least recently used. Reading an entry marks it as recently used, so it survives longer than entries nobody has touched.
  5. 5. Which is the better way to show a circular avatar in Compose?

    Clipping happens at draw time, costs nothing in the cache and does not create extra cache entries the way a pixel transformation does.

Summary

  • Coil's AsyncImage loads a URL, Uri, file or resource off the main thread, shows placeholder, error and fallback images, and cancels work when it leaves the composition.
  • Coil checks the memory cache, then the disk cache, then the network; cache keys include size and transformations, and eviction is LRU.
  • Memory per bitmap is width x height x 4 bytes (by default), so decoding at the display size is the biggest saving; always constrain image size.
  • Prefer Modifier.clip and contentScale over pixel transformations; keep URLs, not bitmaps, in ViewModels and state.
  • Use one ImageLoader for the whole app and give meaningful images a real contentDescription.
  • The Coil and Compose code is read-only; the TryIts simulate the cache and the memory arithmetic.

Next: Dependency Injection Concepts