How to get bitmap from URL using Coil?

14.7k Views Asked by At

I want to load a bitmap from URL and then use palette API to get some colors from that.

On the documentation page, I cannot find the code for getting bitmap directly!

Can anyone help me out?

2

There are 2 best solutions below

8
Pavneet_Singh On BEST ANSWER

You can use target method and cast the drawable to bitmap as

    val loader = ImageLoader(this)
    val req = ImageRequest.Builder(this)
        .data("https://images.dog.ceo/breeds/saluki/n02091831_3400.jpg") // demo link
        .target { result ->
            val bitmap = (result as BitmapDrawable).bitmap
        }
        .build()

    val disposable = loader.enqueue(req)

If you using coroutines then use GetRequest (with overloaded execute method with suspend) in your CoroutineScope as:

  coroutineScope.launch{
    val loader = ImageLoader(this)
    val request = ImageRequest.Builder(this)
        .data("https://images.dog.ceo/breeds/saluki/n02091831_3400.jpg")
        .allowHardware(false) // Disable hardware bitmaps.
        .build()

    val result = (loader.execute(request) as SuccessResult).drawable
    val bitmap = (result as BitmapDrawable).bitmap
}
0
Alireza Ghanbarinia On

according to Coil's own document, you can download a bitmap in the background in the following way:

val request = ImageRequest.Builder(context)
.data(url)
.build()
val drawable = context.imageLoader.execute(request).drawable