'How to load image in Kotlin Compose desktop?

How to load images from the hard disk when using Kotlin compose on the desktop?



Solution 1:[1]

You can get ImageAsset with this function

fun imageFromFile(file: File): ImageAsset {
    return org.jetbrains.skia.Image.makeFromEncoded(file.readBytes()).asImageAsset()
}

Full example:

import androidx.compose.desktop.Window
import androidx.compose.foundation.Image
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.ImageAsset
import androidx.compose.ui.graphics.asImageAsset
import java.io.File

fun main() = Window {
   val file = File("D:\\images\\my_image.PNG")
   val image = remember { imageFromFile(file) }

   Image(asset = image)
}

fun imageFromFile(file: File): ImageAsset {
   return org.jetbrains.skia.Image.makeFromEncoded(file.readBytes()).asImageAsset()
}

Solution 2:[2]

other answers are outdated, as per Compose 1.0.0-beta5 you should do the following:

Image(painterResource("image.jpg"))

if you want to load a bitmap only

val bitmap = useResource("image.jpg") { loadImageBitmap(it) }

Only the file name is required (not full path), but make sure that your resources are in src/main/resources/image.jpg

Solution 3:[3]

This worked for me.

 Image(bitmap = imageFromResource("image.png"),
       "image",
 )

contentDescription is necessary, but can be anything you'd like. You can also add modifiers such as

val imageModifier = Modifier
   .height(240.dp)
   .fillMaxWidth()
   .clip(RoundedCornerShape(12.dp))

Image(bitmap = imageFromResource("header.png"),
      "image",
      imageModifier,
      contentScale = ContentScale.Fit
    )

Solution 4:[4]

Try this one:

import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.res.loadImageBitmap
import java.io.File


val file = File(path)
val imageBitmap: ImageBitmap = remember(file) {
    loadImageBitmap(file.inputStream())
}

Image(
    painter = BitmapPainter(image = imageBitmap),
    contentDescription = null
)

Solution 5:[5]

Image.asImageBitmap() is deprecated. Use new Image.toComposeImageBitmap(). For now (01.04.2022) it's not deprecated yet:

@Composable
fun CanvasArea2() {
    val image = remember { imageFromFile(File("C:/Users/Admin/Desktop/banana.png")) }

    Canvas(modifier = Modifier.background(color = Color(0xFFFFFFFF))) {
        drawImage(image)
    }
}

fun imageFromFile(file: File): ImageBitmap {
    return org.jetbrains.skia.Image.makeFromEncoded(file.readBytes()).toComposeImageBitmap()
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GuilhE
Solution 2 sonique
Solution 3 John Conde
Solution 4 beigirad
Solution 5 badadin