24

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 Answers 2

48

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
}
8
  • What does this line do val disposable = loader.execute(req) Commented Jul 6, 2020 at 13:09
  • @IdrisStack that executes the build request and returns a request disposable that can be used to dispose of queued requests, free up resources, or can invoke await for immediate execution. Commented Jul 8, 2020 at 20:53
  • 1
    Why do you disable hardware? Commented Apr 2, 2021 at 10:05
  • 1
    @AchrafAmil I guess it's was probably because of some stability or compatibility issues at that time. Commented Apr 14, 2021 at 17:05
  • @AchrafAmil because many other native libraries do not support it e.g. Pallette, Firebase ML Kit, ... and you cannot pass it to them it will throw an error
    – Ali Has
    Commented Jul 13, 2022 at 8:23
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.