can I display image in compose desktop if I have b...
# compose-desktop
v
can I display image in compose desktop if I have base64 encoded string? I cant find a way how...
m
Coil can handle that, though I have not tried it on Compose for Desktop.
m
You don’t need any external libraries to do that. It’s all built into Compose. I do it this way:
Copy code
val PNG_BASE64_HEADER = "data:image/png;base64,"

@OptIn(ExperimentalEncodingApi::class)
fun resolveImage(imgBase64: String?): ByteArray? {
	return imgBase64?.let {
		lateinit var strippedImgBase64: String
		try {
			if (it.startsWith(PNG_BASE64_HEADER)) {
				strippedImgBase64 = it.replaceFirst(PNG_BASE64_HEADER,"")
				if (strippedImgBase64.length % 4 != 0) throw Exception("Base64 string length is not a multiple of 4.")
				Base64.Default.decode(strippedImgBase64)
			} else {
				log.debug { "Unknown image format: '${imgBase64.take(20)}'" }
				null
			}
		} catch (e: Exception) {
			throw Exception("Could not resolve image from base 64 string. (start='${imgBase64.take(20)}', end='${imgBase64.takeLast(20)}', base64Length=${strippedImgBase64.length})", e)
		}
	}
}

fun imageBitmapFromBytes(encodedImageData: ByteArray): ImageBitmap {
	return Image.makeFromEncoded(encodedImageData).toComposeImageBitmap()
}