4

如何在 Kotlin Compose 桌面中从远程 url 加载图像?

在 Android 中,它使用大肠杆菌作为官方样本

@Composable
fun NetworkImage(
    url: String,
    modifier: Modifier = Modifier,
    contentScale: ContentScale = ContentScale.Crop,
    placeholderColor: Color? = MaterialTheme.colors.compositedOnSurface(0.2f)
) {
    CoilImage(
        data = url,
        modifier = modifier,
        contentScale = contentScale,
        loading = {
            if (placeholderColor != null) {
                Spacer(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(placeholderColor)
                )
            }
        }
    )
}

bu 作为桌面应用程序,不支持 aar。

4

2 回答 2

4

用于javax.imageio.ImageIO从网络加载图像:

import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import org.jetbrains.skija.Image
import java.io.ByteArrayOutputStream
import java.net.HttpURLConnection
import java.net.URL
import javax.imageio.ImageIO

fun loadNetworkImage(link: String): ImageBitmap {
    val url = URL(link)
    val connection = url.openConnection() as HttpURLConnection
    connection.connect()

    val inputStream = connection.inputStream
    val bufferedImage = ImageIO.read(inputStream)

    val stream = ByteArrayOutputStream()
    ImageIO.write(bufferedImage, "png", stream)
    val byteArray = stream.toByteArray()

    return Image.makeFromEncoded(byteArray).asImageBitmap()
}

然后将其用作:

Image(
    bitmap = loadNetworkImage("Your image link")
)
于 2021-02-02T05:30:51.217 回答
1

我发现的一个简单方法是使用 ktor 将图像作为 byteArray 获取,然后使用 Kotlin 函数 makeFromEncoded 创建一个 ImageBitmap,然后可以将其用于可组合图像

suspend fun loadPicture(url: String): ImageBitmap {
    val image = ktorHttpClient.use { client ->
        client.get<ByteArray>(url)
    }
    return Image.makeFromEncoded(image).asImageBitmap()
}

然后在你的可组合物中

if (imageBitmap != null) {
    Image(bitmap = imageBitmap, "content description")
}
于 2021-06-05T05:39:08.377 回答