Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Bitmap in Kotlin

Tags:

android

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 image , 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.

like image 950
Alex Ioja-Yang Avatar asked Mar 09 '23 07:03

Alex Ioja-Yang


2 Answers

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.

like image 158
Strelok Avatar answered Mar 19 '23 07:03

Strelok


use this:

try {
  val imageBytes =Base64.decode(string,0);
  val image=BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size);
 return image;
} catch(Exception e) {
      e.getMessage();
      return null;
   }
like image 22
Dhruv Tyagi Avatar answered Mar 19 '23 07:03

Dhruv Tyagi