convert string to bitmap android kotlin
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
fun stringToBitmap(encodedString: String): Bitmap? {
val decodedBytes: ByteArray = Base64.decode(encodedString, Base64.DEFAULT)
return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
}
Explanation:
- Import necessary classes:
android.graphics.Bitmap
,android.graphics.BitmapFactory
, andandroid.util.Base64
. - Create a function
stringToBitmap
that takes anencodedString
of typeString
as a parameter. - Decode the Base64-encoded string to a
ByteArray
usingBase64.decode
method, passing theencodedString
andBase64.DEFAULT
flag. - Use
BitmapFactory.decodeByteArray
to convert the decoded byte array back into aBitmap
. Parameters passed are the decoded bytes (decodedBytes
), starting index (0), and length (size ofdecodedBytes
). - Return the resulting
Bitmap
object ornull
if the conversion fails.