如何使用线圈从 URL 获取位图?

Chi*_*mar 6 android palette image-load kotlin coil

我想从 URL 加载位图,然后使用调色板 API 从中获取一些颜色。

在文档页面,我找不到直接获取位图的代码!

谁能帮我吗?

Pav*_*ngh 13

您可以使用target方法并将可绘制对象转换bitmap

    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)
Run Code Online (Sandbox Code Playgroud)

如果您使用协程,则在您的 CoroutineScope 中使用GetRequest(使用重载execute方法suspend)作为:

  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
}
Run Code Online (Sandbox Code Playgroud)