Hannibal House
Hannibal House

Reputation: 11

Flutter how to display an image from base64

I am using an API that brings data like this:

"photos": [
    {
      "id": 6,
      "name": "Seguridad",
      "base64Image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...",
    }
]

What I need to do is to display the photos in a screen in my App. I've searched how to do it but I kept having the same error message: Exception: Invalid Image Data. I've read that what I need to do is to encode my base64 String, then decode that and then use it on Image.Memory, like this:

String image = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...';
var bs64 = base64.encode(utf8.encode(example));
Uint8List decodedImage = base64.decode(bs64);
// --------
Image.memory(decodedImage)

I've tried using different base64 strings but the error is always there. I appreciate any help with this.

Upvotes: 1

Views: 1758

Answers (1)

HW Kim
HW Kim

Reputation: 475

Because you are not decoding base64 string.

You have to remove data:image/jpeg;base64, (comma included)

you have to remove that because that data:image/jpeg;base64, just indicates that the string is image data with jpeg format which is encoded as base64 string.

So, the actual base64 data starts after it and you have to decode that.

Upvotes: 2

Related Questions