5

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?

YaMiN
  • 929
  • 3
  • 17
Chintan Parmar
  • 795
  • 6
  • 12

1 Answers1

8

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.execute(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
}
HBB20
  • 1,645
  • 18
  • 26
Pavneet_Singh
  • 34,557
  • 5
  • 43
  • 59
  • What does this line do `val disposable = loader.execute(req)` – Idris Stack Jul 06 '20 at 13:09
  • @IdrisStack that executes the build request and returns a [request disposable](https://coil-kt.github.io/coil/api/coil-base/coil.request/-request-disposable/) that can be used to dispose of queued requests, free up resources, or can invoke `await` for immediate execution. – Pavneet_Singh Jul 08 '20 at 20:53
  • Why do you disable hardware? – Achraf Amil Apr 02 '21 at 10:05
  • @AchrafAmil I guess it's was probably because of some [stability or compatibility issues](https://stackoverflow.com/a/45660636/4936904) at that time. – Pavneet_Singh Apr 14 '21 at 17:05