Fun with Text to Image in Android
Have you display any Image in your App? Of course you have! How have you done it?… Let me guess…
- Have an image asset (either PNG, JPEG, WEBP or VectorDrawable) in your resource folder.
- Load the image from an image URL
- Payload sent an Image URL that contains image URL, and you load the image.
What if I say, let’s load it from TEXT is the other option? What!?
Yes, that’s possible!
Base64 format
There’s a format call Base64 format that could represent any Binary data in Text. This includes any image file (JPEG, PNG, WEBP, BMP, you name it).
To decode
Assuming you have a Base64 Text representation of an image, to decode it back just use Base64.decode
as below. And for my case, I’ll translate into Bitmap using BitmapFactory.decodeByteArray
.
Note: the
BitmapFactory.decodeByteArray
could decode BMP, PNG, JPEG etc, any image format that is listed in https://developer.android.com/guide/topics/media/media-formats#core
fun String.decodeBase64IntoBitmap(): Bitmap {
val imageBytes = Base64.decode(this, Base64.DEFAULT)
return BitmapFactory.decodeByteArray(
imageBytes, 0, imageBytes.size)
}