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

How to load image from remote url in Kotlin Compose desktop?

如何在 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。

使用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")
)

我发现的一种简单方法是使用 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")
}