I have a Base64 String that represents a BitMap image.
I need to transform that String into a BitMap image again to use it on a ImageView in my Android app
How to do it?
I have a Base64 String that represents a BitMap image.
I need to transform that String into a BitMap image again to use it on a ImageView in my Android app
How to do it?
You can use this code to decode: -
val imageBytes = Base64.decode(base64String, Base64.DEFAULT)
val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length)
imageView.setImageBitmap(decodedImage)
You can use the android methods
Here imageString is your base64String of image.
Here is the java code:
byte[] decodedByte = Base64.decode(imageString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedByte, 0, decodedString.length);
Here is the kotlin code:
val decodedByte = Base64.decode(imageString, Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(decodedByte, 0, decodedString.length)
After that, you can set it into the image view
yourimage.setImageBitmap(bitmap);
From the answer above, I made it as a function.
KOTLIN: you could create a function like this
fun decodePicString (encodedString: String): Bitmap {
val imageBytes = Base64.decode(encodedString, Base64.DEFAULT)
val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
return decodedImage
}
then call it and set it to your imgView like this:
val mImgView = findViewById<ImageView>(R.id.imageView)
mImageView.setImageBitmap(decodePicString(your encoded string for the picture))
For those who seek a general answer for Base64 conversions (not just Android):
You can make use of java.util.Base64
to
encode
val imageString = Base64.getEncoder().encode(imageBytes)
to
decode
val imageBytes = Base64.getDecoder().decode(imageString)
In Kotlin You can just use decode function for byteArray...
private fun stringToBitmap(encodedString: String): Bitmap {
val imageBytes = decode(encodedString, DEFAULT)
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
}