Android: Coil, Glide and BlurHash Placeholders
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Baseline date: 2026-10-07. Coil 3.6.3 and Glide 5.0.9 are the latest releases on Maven Central on that date. The
mechanics of both libraries (the request pipeline, ImageRequest, transformations, preloading, the Views and RecyclerView
integrations) are in Image Loading, Caching and Transformations with Coil
and Glide. This page does not repeat them. It covers what a media backend adds: choosing the variant that matches the
screen, configuring the caches, and showing a BlurHash while the image loads. The backend side is in
responsive images and thumbnails and
the BlurHash algorithm.
Ask for the right size
An app downloads whatever URL it is given. Pick the variant from the API’s list (see the JSON in responsive images) that is at least as wide as the target size in pixels, and prefer AVIF or WebP when the API offers them. WebP is supported by Android since API 14 for lossy and API 18 for lossless and alpha. AVIF decoding is built into the platform from Android 12 (API 31). On older devices, request the WebP or JPEG variant. A small helper keeps that decision in one place:
data class Variant(val format: String, val width: Int, val url: String)
fun bestVariant(variants: List<Variant>, targetWidthPx: Int): Variant {
val formats = if (android.os.Build.VERSION.SDK_INT >= 31) listOf("avif", "webp", "jpeg") else listOf("webp", "jpeg")
return formats.firstNotNullOf { format ->
variants.filter { it.format == format }
.sortedBy { it.width }
.let { sorted -> sorted.firstOrNull { it.width >= targetWidthPx } ?: sorted.lastOrNull() }
}
}
Reference: Android supported media formats.
Coil 3
// build.gradle.kts
dependencies {
implementation("io.coil-kt.coil3:coil-compose:3.6.3")
implementation("io.coil-kt.coil3:coil-network-okhttp:3.6.3") // network fetcher: pick one coil-network-* artifact
}
Coil 3 split the network layer into separate artifacts, so a coil-network-okhttp (or coil-network-ktor3) artifact is
required to load URLs. Configure the loader once in the Application, with explicit cache sizes:
import android.app.Application
import coil3.ImageLoader
import coil3.PlatformContext
import coil3.SingletonImageLoader
import coil3.disk.DiskCache
import coil3.memory.MemoryCache
import coil3.request.crossfade
class App : Application(), SingletonImageLoader.Factory {
override fun newImageLoader(context: PlatformContext): ImageLoader =
ImageLoader.Builder(context)
.memoryCache { MemoryCache.Builder().maxSizePercent(context, 0.25).build() }
.diskCache {
DiskCache.Builder()
.directory(context.cacheDir.resolve("image_cache"))
.maxSizeBytes(256L * 1024 * 1024)
.build()
}
.crossfade(true)
.build()
}
import coil3.compose.AsyncImage
import coil3.request.ImageRequest
@Composable
fun Cover(url: String, blurhash: String?, modifier: Modifier = Modifier) {
val placeholder = rememberBlurHashPainter(blurhash) // defined below
AsyncImage(
model = ImageRequest.Builder(LocalContext.current).data(url).build(),
contentDescription = null,
placeholder = placeholder,
contentScale = ContentScale.Crop,
modifier = modifier,
)
}
Coil sizes the decoded bitmap to the composable’s size, so a 1280 pixel file shown in a 200 dp slot is not kept at full size
in memory. The disk cache stores the downloaded file. Coil also honours the server’s Cache-Control headers, which is
why immutable, versioned variant URLs from the CDN work well. References: Coil
getting started, image loaders and
network.
BlurHash as a placeholder
Two options. The woltapp Kotlin decoder is a single file to copy
into the project (BlurHashDecoder), and vanniktech/blurhash (0.3.0) is a
published Kotlin Multiplatform library, see
Kotlin Multiplatform and Flutter. With the woltapp
decoder:
import android.graphics.Bitmap
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.graphics.painter.Painter
@Composable
fun rememberBlurHashPainter(hash: String?, width: Int = 32, height: Int = 32): Painter? =
remember(hash) {
hash?.let { BlurHashDecoder.decode(it, width, height) } // returns Bitmap?
?.let { BitmapPainter(it.asImageBitmap()) }
}
Decode at 32 by 32 pixels and let Compose scale it, as on the web. The decoder is fast, but do not decode inside a
list item on every recomposition: the remember(hash) above caches per item, and BlurHashDecoder keeps its own
cosine table cache. With Views and Glide, set the decoded BitmapDrawable as placeholder(...).
Glide 5
dependencies {
implementation("com.github.bumptech.glide:glide:5.0.9")
ksp("com.github.bumptech.glide:ksp:5.0.9")
implementation("com.github.bumptech.glide:compose:<version>") // Compose integration, see the Glide releases page
}
Glide.with(imageView)
.load(bestVariant(variants, imageView.width).url)
.diskCacheStrategy(DiskCacheStrategy.ALL) // cache the original file and the resized result
.placeholder(BitmapDrawable(imageView.resources, BlurHashDecoder.decode(hash, 32, 32)))
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageView)
DiskCacheStrategy.ALL stores both the downloaded data and the transformed result. AUTOMATIC (the default) is a
good choice for remote images, since it stores the original for remote data and only the transformed version for local
data, and NONE disables disk caching. In Compose, Glide offers GlideImage in its Compose integration, which is
marked experimental, so opt in with @OptIn(ExperimentalGlideComposeApi::class) and check the release notes of the
Compose artifact. Use Coil for new Compose-only apps, and keep Glide where an existing Views and RecyclerView screen
already uses it. References: Glide caching and
Glide Compose integration.
Fresco
Fresco (from Meta) manages its own memory pool and supports progressive JPEG and animated images. It is the legacy choice and is still used in React Native on Android. For a new native app, Coil or Glide is simpler.
From a variant to pixels in memory
The cheapest byte is the one that is never downloaded, and the cheapest bitmap is the one that is never decoded at full size. Both libraries run the same stages for every request, and each stage is a place to save work.
A decoded bitmap costs width times height times 4 bytes (ARGB_8888), whatever the size of the compressed file. The
running example of this section is the cover b81f of the backend pages (2400 by 3600 pixels, variants 320, 640 and 1280
pixels wide). The numbers below come from the arithmetic that the platform uses, evaluated for that cover:
| What is decoded | Pixels | Memory |
|---|---|---|
The original, 2400 by 3600 |
8,640,000 |
32.96 MiB |
The 1280 pixel variant, 1280 by 1920 |
2,457,600 |
9.38 MiB |
The 640 pixel variant, 640 by 960 |
614,400 |
2.34 MiB |
The 320 pixel variant, 320 by 480 |
153,600 |
0.59 MiB |
A grid that keeps thirty covers in memory costs 70 MiB at 640 pixels and 989 MiB at full size, which is why choosing the
variant is the first optimisation and downsampling at decode time is the second. Downsampling matters when the variant is
wider than the slot, for example a 640 pixel file shown in a 300 pixel slot, or an original picked from the gallery.
BitmapFactory can only decode at a power-of-two sample size, and the algorithm from the Android documentation rounds in
the safe direction (never smaller than the request):
fun calculateInSampleSize(width: Int, height: Int, reqWidth: Int, reqHeight: Int): Int {
var inSampleSize = 1
if (height > reqHeight || width > reqWidth) {
val halfHeight = height / 2
val halfWidth = width / 2
while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
inSampleSize *= 2
}
}
return inSampleSize
}
fun decodeSampled(path: String, reqWidth: Int, reqHeight: Int): Bitmap? {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } // reads the header only
BitmapFactory.decodeFile(path, bounds)
val options = BitmapFactory.Options().apply {
inSampleSize = calculateInSampleSize(bounds.outWidth, bounds.outHeight, reqWidth, reqHeight)
}
return BitmapFactory.decodeFile(path, options)
}
Evaluated for the original cover, the function gives:
| Requested size | inSampleSize |
Decoded size | Memory |
|---|---|---|---|
480 by 720 (a 160 by 240 dp slot at 3x) |
4 |
600 by 900 |
2.06 MiB |
720 by 1080 |
2 |
1200 by 1800 |
8.24 MiB |
1280 by 1920 |
1 |
2400 by 3600 |
32.96 MiB |
The second row shows the limit of inSampleSize: a request for 720 by 1080 can only be answered with 1200 by 1800, a
bitmap 2.8 times larger than needed. On API 28 and later, ImageDecoder removes the restriction and also applies the EXIF
orientation, which BitmapFactory ignores:
fun decodeExact(context: Context, uri: Uri, widthPx: Int): Bitmap {
val source = ImageDecoder.createSource(context.contentResolver, uri)
return ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
val scale = widthPx.toFloat() / info.size.width
if (scale < 1f) decoder.setTargetSize(widthPx, (info.size.height * scale).toInt())
}
}
Coil and Glide do all of this for you from the size of the target, so call these functions yourself only for images that do not go through a library (a picker result that you are about to compress, see device-side compression and uploads).
Worked example: a cover grid
A grid of covers combines the pieces above. The API returns the JSON of the responsive images page. Each tile is 160 by 240 dp, so the target is the slot width in pixels, which the composable reads from the layout instead of guessing the density:
@Serializable
data class Cover(val id: String, val width: Int, val height: Int, val blurhash: String, val variants: List<Variant>)
@Composable
fun CoverTile(cover: Cover, modifier: Modifier = Modifier) {
val density = LocalDensity.current
BoxWithConstraints(modifier.aspectRatio(cover.width.toFloat() / cover.height)) {
val targetPx = with(density) { maxWidth.roundToPx() }
val variant = remember(cover.id, targetPx) { bestVariant(cover.variants, targetPx) }
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(variant.url)
.memoryCacheKey("${cover.id}/${variant.format}/${variant.width}") // explicit and stable
.build(),
contentDescription = null,
placeholder = rememberBlurHashPainter(cover.blurhash),
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
)
}
}
The aspectRatio modifier reserves the tile before the file arrives, for the same reason that the web pages set width
and height on an image: nothing shifts when the picture appears. The variant function returns the following for the
cover:
| Device | Slot in px | Variant chosen |
|---|---|---|
A phone with API 34, 200 dp at 2.625x |
525 |
|
A phone with API 29, 360 px slot |
360 |
|
To warm the cache for the next page of a list, enqueue requests on the same loader. The disk cache stores the downloaded file, so the request only has to be large enough to be useful once the tile appears:
fun preloadCovers(context: Context, covers: List<Cover>, slotPx: Int) {
val loader = SingletonImageLoader.get(context)
covers.forEach { cover ->
val variant = bestVariant(cover.variants, slotPx)
loader.enqueue(ImageRequest.Builder(context).data(variant.url).size(slotPx, slotPx * 3 / 2).build())
}
}
Glide: module settings and request options
Glide is configured once in an AppGlideModule, which the KSP processor shown above discovers. The module below uses a
named 256 MiB disk cache, and the requests then state the size they need:
@GlideModule
class MediaGlideModule : AppGlideModule() {
override fun applyOptions(context: Context, builder: GlideBuilder) {
builder.setDiskCache(InternalCacheDiskCacheFactory(context, "covers", 256L * 1024 * 1024))
}
}
Glide.with(imageView)
.load(variant.url)
.override(widthPx, widthPx * 3 / 2) // decode at this size, never the file's size
.centerCrop()
.thumbnail(0.25f) // a quarter-size decode shows first, from the same file
.into(imageView)
thumbnail(float) is a second, smaller decode of the same model. It is useful when the full decode is slow, and it is
unrelated to the BlurHash placeholder, which needs no network at all. Glide builds its cache key from the URL, the
requested size and the transformations, so immutable variant URLs from the CDN never need a signature. A mutable URL
needs signature(ObjectKey(version)) with a version from the API. For RecyclerView, Glide’s RecyclerViewPreloader (in the
recyclerview-integration artifact) preloads the next few items while the user scrolls. Glide cannot clear its disk cache
on the main thread (Glide.get(context).clearDiskCache() must run on a background thread), while clearMemory() must run
on the main thread.
Choosing between the two
| Coil 3 | Glide 5 | |
|---|---|---|
Language and UI |
Kotlin, coroutines, Compose first, multiplatform |
Java and Kotlin, Views first, Compose through an integration |
Sizing |
From the composable or |
|
Disk cache |
|
|
Memory |
|
|
Pick it |
New Compose apps and KMP |
Existing RecyclerView code and its preloader |
The mapping to the backend is the same in both, and the placeholder is the same decoded BlurHash painter or drawable.
Video and uploads
Android video is covered in Media3 and compressing before an upload in device-side compression and uploads.
Related pages
-
Image Loading, Caching and Transformations with Coil and Glide
-
Native HTML Images and Lazy Loading is the browser counterpart of the variant choice made here.
-
Responsive Images and Thumbnails produces the variants.