Alex Ioja-Yang Alex Ioja-Yang -3 years ago 321
Android Question

String to Bitmap in Kotlin

I'm new to Kotlin and I can't seem to work this one out. I get a base64String and I need an image.

I did:

val imageBytes = string.toByteArray(). // string is the base64image
val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

Problem is that when I try to access the
, I get a
SkAndroidCodec::NewFromStream returned null
message in the log. I wanted to use it inside a method with a return but it kept crashing on
return image

How do I convert it correctly?

I have checked and string is not empty, imageBytes has content and imageBytes.size is over 60000. The same string I use in swift and it converts image without any modifications, so I am confident the string is not the problem.

Answer Source
val imageBytes = Base64.decode(string, 0)
val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

That is all. You just have to decode the base 64 string first into a byte array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download