Home > OS >  Decoding base64 string to image in flutter (Invalid character exception)
Decoding base64 string to image in flutter (Invalid character exception)

Time:07-25

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

CodePudding user response:

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'), '')),
  • Related