0

Basically I'm trying to convert a base64 jpeg image to normal image in flutter using

Image.memory(base64Decode(stringBase64))

the image initially used to be jp/2 format which isn't supported by flutter so i converted the jp/2 base64 string to bitmap in java and then to base64 string jpeg to be able to decode it in flutter using this code :

public static String encodeToBase64(Bitmap image)
{
    Bitmap immagex=image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

    return imageEncoded;
}

how ever when i try to decode this base64 string in flutter i'm getting this error

Invalid character (at character 77) /9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAIQAABtbnRyUkdC

which is pointing to the last C in the given line.

i don't seem understand where does the issue come from since i can convert my base64 string to image online but in flutter it throws that exception every time

Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
  • Most likely your base64 string contains whitespace (such as being split across multiple lines). [Dart's base64 decoder does not accept whitespace](https://github.com/dart-lang/sdk/issues/29434), so you will need to remove it yourself first (e.g. `base64Decode(stringBase64.replaceAll(RegExp(r'\s'), ''))`). – jamesdlin Jul 24 '22 at 07:56

2 Answers2

0

thank you very much @Jamesdlin for the solution that was given in the comments

The issue was due to whitespace in the base64 string , solved by using

 base64.decode(photoBase64.replaceAll(RegExp(r'\s'), '')),
0

If your URI contains data after the comma as it is defined by RFC-2397. Dart's Uri class is based on RFC-3986, so you can't use it.

Split the string by a comma and take the last part of it:

String uri = 'data:image/gif;base64,...';
Uint8List _bytes = base64.decode(uri.split(',').last);

REFERENCE: https://stackoverflow.com/a/59015116/12382178