How can i convert base64 to bitmap in compose mult...
# compose-ios
s
How can i convert base64 to bitmap in compose multiplatform? whats the alternative of
android.graphics.BitmapFactory
?
m
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
thank you Michael, but i get an error on Image.makeFromEncoded...
Function invocation 'Image(...)' expected
did you also face that?
m
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
ahh i'm looking for any common main which could work on both android and ios. btw thanks
m
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
It works, thank you. ❤️
897 Views