Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get bitmap from URL using Coil?

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?

like image 515
Chintan Parmar Avatar asked May 19 '20 13:05

Chintan Parmar


1 Answers

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
}
like image 119
Pavneet_Singh Avatar answered Oct 04 '22 01:10

Pavneet_Singh