Search code examples
imagebitmapkotlin-multiplatform

Load image from disk in kotlin multiplatform


I have simple kotlin multiplatform project. And I want to display some PNG from my disk. How can I do that? For example, my image is located in "D:\sample_image.png". I do not want to use resources at all.

Using painter = painterResource("D:\sample_image.png") does not work as this is not the resource.

FileResourceLoader is not available since it's Compose Desktop thingy.

Please note that I'm using Kotlin Multiplatform, and I need universal solution.

Any help is appreciated, thanks!


Solution

  • OK, so I resolved it... kinda.

    CommonMain:

    expect fun createBitmapFromFile(filepath: String): ImageBitmap?
    

    jvmMain:

    actual fun createBitmapFromFile(filepath: String): ImageBitmap? {
        val file = File(filepath)
        return if (file.exists()) {
            val inputStream = file.inputStream()
            return loadImageBitmap(inputStream)
        } else {
            null
        }
    }
    

    iosMain: AI generated, and I don't have option to test it. If anyone is kind enough to try it out and confirm it works, I would really appreciate it.

    actual fun createBitmapFromFile(filePath: String): ImageBitmap? {
        val fileURL = NSURL.fileURLWithPath(filePath)
        val imageData = NSData.dataWithContentsOfURL(fileURL)
        val uiImage = UIImage.imageWithData(imageData)
    
        return if (uiImage != null) {
            return uiImage.toBitmap()
        } else {
            null
        }
    }
    
    private fun UIImage.toBitmap(): ImageBitmap {
        val cgImage = this.CGImage
        val data = cgImage.dataProvider?.data
        val bytes = data?.readBytes()?.toUByteArray()
        return Image.makeFromEncoded(bytes).asImageBitmap()
    }