https://kotlinlang.org logo
#compose-ios
Title
# compose-ios
s

Shoaib khalid

10/21/2023, 2:57 PM
How can i convert base64 to bitmap in compose multiplatform? whats the alternative of
android.graphics.BitmapFactory
?
m

Michael Paus

10/21/2023, 3:28 PM
That’s how I do it in my code:
Copy code
import org.jetbrains.skia.Image

	val PNG_BASE64_HEADER = "data:image/png;base64,"

    @OptIn(ExperimentalEncodingApi::class)
    private fun resolveImage(imgBase64: String?): ByteArray? {
        try {
            return imgBase64?.let {
                if (it.startsWith(PNG_BASE64_HEADER)) {
                    Base64.Default.decode(it.replaceFirst(PNG_BASE64_HEADER,""))
                } else {
                    log.debug { "Unknown image format: '${imgBase64.take(20)}'" }
                    null
                }
            }
        } catch (e: Exception) {
            throw Exception("Could not resolve image from base 64 string.", e)
        }
    }
    
    fun imageBitmapFromBytes(encodedImageData: ByteArray): ImageBitmap {
        return Image.makeFromEncoded(encodedImageData).toComposeImageBitmap()
    }
Should also work on iOS but I haven’t tested it there.
s

Shoaib khalid

10/21/2023, 3:41 PM
thank you Michael, but i get an error on Image.makeFromEncoded...
Function invocation 'Image(...)' expected
did you also face that?
m

Michael Paus

10/21/2023, 4:06 PM
No. This is the original code (copied directly from some other project) which I use for iOS.
Copy code
override fun imageBitmapFromBytes(encodedImageData: ByteArray): ImageBitmap {
        return Image.makeFromEncoded(encodedImageData).toComposeImageBitmap()
    }
Check the import statement for Image
Copy code
import org.jetbrains.skia.Image
This code is of course platform specific, so you can’t use it in common.
s

Shoaib khalid

10/21/2023, 4:17 PM
ahh i'm looking for any common main which could work on both android and ios. btw thanks
m

Michael Paus

10/21/2023, 4:39 PM
On Android you would just use this corresponding code variant.
Copy code
override fun imageBitmapFromBytes(encodedImageData: ByteArray): ImageBitmap {
    return BitmapFactory.decodeByteArray(encodedImageData, 0, encodedImageData.size).asImageBitmap()
}
In my code these variants are part of a class which is declared via expect/actual. You can then call
imageBitmapFromBytes
in your common code.
s

Shoaib khalid

10/22/2023, 9:59 AM
It works, thank you. ❤️
19 Views