How to get bitmap from URL using Coil?
Asked Answered
D

2

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?

Demetricedemetris answered 19/5, 2020 at 13:30 Comment(0)
C
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
}
Chromous answered 19/5, 2020 at 14:6 Comment(8)
What does this line do val disposable = loader.execute(req)Detect
@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.Chromous
Why do you disable hardware?Swore
@AchrafAmil I guess it's was probably because of some stability or compatibility issues at that time.Chromous
@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 errorEun
You should avoid creation of ImageLoader every time image load is required because of this issue issuetracker.google.com/issues/231499040#comment3Larson
if image was previously loaded and available in cache (memory/disk) then it will return it instantly? basically I have the list of times with image and user can click share button on each item to share text and image content of specific itemWashtub
@Washtub Coil uses in-memory cache so you can try running a test to load large images and see if it always download the images or how efficient it is to use cache.Chromous
H
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
Hanhana answered 27/3 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.