when using `accompanist-coil` to load images, how ...
# compose
m
when using
accompanist-coil
to load images, how can I get loaded image back? same as you can with
Coil
:
Copy code
val request = ImageRequest.Builder(context)
    .data("<https://www.example.com/image.jpg>")
    .target { drawable ->
        // Handle the result.
    }
    .build()
or add
Target
on Glide?
z
One way would be to check the
loadState
on the
LoadPainter
returned from `rememberCoilPainter`: when it’s
Loaded
, the painter will be ready to draw the image. https://google.github.io/accompanist/api/imageloading-core/imageloading-core/com.google.accompanist.imageloading/-load-painter/index.html#%5B[…]4529
rememberCoilPainter
also lets you pass a function that customizes the
ImageRequest.Builder
, but idk what happens if you try setting a target there, since i assume
rememberCoilPainter
sets the target itself.
m
@Zach Klippenstein (he/him) [MOD]
ImageLoadState.Success
exposes
Painter
but how can I get
Bitmap
from it?
z
You don’t need to tag people who have replied to threads, they get notified automatically
I don’t think you can get a bitmap from it – if you need to use coil to load a bitmap, just use coil directly, you don’t need to use accompanist at all.
m
I will try, thanks
c
Accompanist now deals exclusively in `Painter`s, as the returned image could be a GIF, etc. +1 to what @Zach Klippenstein (he/him) [MOD] said about using Coil directly if you need a bitmap. You’ll be using the same cache, etc as Accompanist.
m
big thanks to both of you, I’ve succeeded with using Coil directly
👍 2
did you mean something like this?
Copy code
@Composable
fun CoilImage(
    modifier: Modifier = Modifier,
    url: String,
) {
    val coroutineScope = rememberCoroutineScope()
    val loader = ImageLoader(LocalContext.current)
    var image by remember { mutableStateOf(ImageBitmap(1, 1)) }
    val target = remember {
        object : Target {
            override fun onSuccess(result: Drawable) {
                image = result.toBitmap().asImageBitmap()
            }
        }
    }

    val request = ImageRequest.Builder(LocalContext.current).run {
        data(url)
        target(target)
        scale(Scale.FILL)
        allowHardware(false)
        build()
    }

    LaunchedEffect(url) {
        loader.enqueue(request)
    }

    Image(
        modifier = modifier.height(250.dp),
        bitmap = image,
        contentScale = ContentScale.FillWidth,
        contentDescription = null,
    )
}