androidkotlinpaletteimage-loadcoil

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?


Solution

  • 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
    }