Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Compose how to access drawable once Coil loads image from URL

I am using accompanist-coil:0.12.0. I want to load image from a url and then pass the drawable to a method. I am using this:

val painter = rememberCoilPainter(
        request = ImageRequest.Builder(LocalContext.current)
            .data(imageUrl)
            .target {
                viewModel.calcDominantColor(it) { color ->
                    dominantColor = color
                }
            }
            .build(),
        fadeIn = true
    )

and then passing the painter to Image like this:

Image(
   painter = painter,
   contentDescription = "Some Image",
)

The image loads without any problem but the method calcDominantColor is never called.
Am I doing it the wrong way?

UPDATE:
I was able to call the method using Transformation in requestBuilder but I am not sure, if this is how it is supposed to be done because I am not actually transforming the Bitmap itself:

val painter = rememberCoilPainter(
        request = entry.imageUrl,
        requestBuilder = {
            transformations(
                object: Transformation{
                    override fun key(): String {
                        return entry.imageUrl
                    }
                    override suspend fun transform(
                        pool: BitmapPool,
                        input: Bitmap,
                        size: Size
                    ): Bitmap {
                        viewModel.calcDominantColor(input) { color ->
                            dominantColor = color
                        }
                        return input
                    }
                }
            )
        }
    )

This works fine for first time but when the composable recomposes, transformation is returned from cache and my method doesn't run.

like image 704
Md Azharuddin Avatar asked Jun 23 '21 06:06

Md Azharuddin


1 Answers

I think you want to use LaunchedEffect along with an ImageLoader to access the bitmap from the loader result.

    val context = LocalContext.current

    val imageLoader = ImageLoader(context)

    val request = ImageRequest.Builder(context)
        .transformations(RoundedCornersTransformation(12.dp.value))
        .data(imageUrl)
        .build()

    val imagePainter = rememberCoilPainter(
        request = request,
        imageLoader = imageLoader
    )

    LaunchedEffect(key1 = imagePainter) {
        launch {
            val result = (imageLoader.execute(request) as SuccessResult).drawable
            val bitmap = (result as BitmapDrawable).bitmap
            val vibrant = Palette.from(bitmap)
                .generate()
                .getVibrantColor(defaultColor)
            // do something with vibrant color
        }
    }
like image 99
jacoballenwood Avatar answered Sep 30 '22 15:09

jacoballenwood