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

Viewed 2685

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

in Android it use coli as official sample

@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 as desktop application, aar is not supported.

2 Answers

Use javax.imageio.ImageIO to load an image from network:

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()
}

And then use it as:

Image(
    bitmap = loadNetworkImage("Your image link")
)

A simple way I found was to use ktor to get the image as a byteArray and then use the Kotlin function makeFromEncoded to create a ImageBitmap which can then be used in a Composable Image

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

Then inside your composable

if (imageBitmap != null) {
    Image(bitmap = imageBitmap, "content description")
}
Related