I do that massively to extract such images from HTML in a Compose desktop app. I use the following code to get the encoded bytes which assumes that all images are PNGs but you get the point:
Copy code
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)
}
}