在台式机上使用Kotlin compose时如何从硬盘加载图像?
答案 0 :(得分:3)
这对我有用。
Image(bitmap = imageFromResource("image.png"),
"image",
)
contentDescription
是必需的,但可以是您想要的任何内容。您还可以添加修饰符,例如
val imageModifier = Modifier
.height(240.dp)
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
Image(bitmap = imageFromResource("header.png"),
"image",
imageModifier,
contentScale = ContentScale.Fit
)
答案 1 :(得分:1)
您可以使用此功能获取ImageAsset
fun imageFromFile(file: File): ImageAsset {
return org.jetbrains.skija.Image.makeFromEncoded(file.readBytes()).asImageAsset()
}
完整示例:
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.skija.Image.makeFromEncoded(file.readBytes()).asImageAsset()
}