Decoding base64 string to image in flutter (Invalid character exception) - flutter

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

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

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

Related

Decode utc8 character from string Flutter

I'm unable to decode the utc8 characters from string.
Below line getting from API
replace the cable if a fault is found รข for example
actual string
replace the cable if a fault is found - for example
Can any one help me how to fix this ?
Thanks!!!
You can use the Charset Detector Flutter Charset Detector Package to convert it to the correct encoding.
I already used it, and it works perfectly. You just have to convert the body of the response to the desired encoding.
You pass the bodyBytes field to the package autoDecode method.
Uint8List bodyBytes = response.bodyBytes;
DecodingResult decoded = (await CharsetDetector.autoDecode(bodyBytes));
String charset = decoded.charset;
String bodyInRightEncodage = decoded.string;
The response field is a http response object.
Below line is working fine
jsonDecode(utf8.decode(response.bodyBytes, allowMalformed: true));

How to decode or convert base64 string url to UintList in Dart?

I got this base64Result from canvas.toDataURL() but I having difficulties parsing in Dart to 'UintList'
import 'dart:convert';
final String base64Result = result.toString();
print("$logTrace calling web function done ${base64Result.length}");
final bytes = base64Url.decode(base64Result);
character (at character 5)
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARwAAAIrCAYAAAA9YyZoAAAgAElEQ...
^
'data:image/png;base64,' is part of the data URL, not part of a base-64 string. You need to extract the base-64 data from the URL first.
Luckily, the UriData class can do this all for you:
final bytes = UriData.parse(base64Result).contentAsBytes();

format exception when using Image.memory to load base64 image in flutter

Now I am using this code to load a base64 image stream in flutter:
var foregroundImage;
if(counter.value.iconData != null && counter.value.iconData != "") {
Uint8List base64Decode(String source) => base64.decode(source);
Uint8List uint8list = base64Decode(counter.value.iconData);
foregroundImage = Image.memory(uint8list);
}else{
foregroundImage = defaultImage;
}
when the stream like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACXElEQVR4XsWXTU8TURSGu/AHuOnMlMbYWorKt1sVKDGiIf4BdUUQXWHiAnDXlERd4oJ+4rbFFa5w1fYvNE0wuJIFf8E0bZr2OO+UO7T3ozMEO3OSd3PPued5Z+a2995AQBKaFtV1PfRB041KUAudBzWjbYquqDbmoofVy+zJc4RIJBI3NM1ImpP+ShpeS+iJ3mDwXCsikcjN3hOLk/+nwABrAG49uQdwJrAG3gReDV80aoF5AY/qo/jmTuqtCXNhYoXySa8EdiCoG1U+4ZWwFgIXv3MhyWtyaloYU8l9bejcNDD8T2Z27gGdnPyibrdLpcPvpBtjQg0TcsXSoVWLOZjL13BqwwA/aAsN/pydUX8cHf2QmsAYcv2RyWQpNj4h1PZLaUAGZ8GbkMHz+QKlUrv06fOXoSakBnh4s9mk4+Ofl93p0oQKvrz8hHK5vKVhJgQDMvjLV6+tHBqzOD39Tfcnp6Rw1D58tEDpdMbRxICBmdl5JZwJAMCnZ+aUcKbHC4uCiTuxuNpAsViym7VaLQHOFJ+45whXmdh4+05toHDwzW7Y6XRoc/O90FD1zfk6pqcrzymbzdkG1tbW1QbG43epXq/bjXkT14Unkym6HYmqDahMrL/ZGAlcakBmAmvhKvCVZ+7gSgMQM1Gr1QR4oXAg1DMtLiVcwyGlAQgmyuWyazi0vf3RNRxy3IxgolKtUqPRoL29r0Ke1+rqC9pPp2lra8cRHuxtRu6247HwLWFMJSMUFsbkMrdjLw+jvKwDie9HMt8Ppb4fyxG+X0wQvl7NWPh6Oe0PL6/n/wCHXSY6hk0RUwAAAABJRU5ErkJggg==
show error formatexception: invalid character:
when I am parse the stream in web, it could parse successfully. why would this happen? what should I do to fix it?
The problem is that the actual base64 encoded image is after the "base64," word.
Since base64 can not contain comma symbol - you can just split the string by it and take the last part:
counter.value.iconData.split(',').last
base64Decode decodes pure base64, remove data:image/png;base64, and give rest to base64Decode function

Why is the base64 string not showing completely?

So this is my code
_image1 = File(pickedImage.path);
List<int> imageBytes = _image1.readAsBytesSync();
String base64Image = base64.encode(imageBytes);
_shcpImg = base64Image;
But when I print the string _shcpImg, it just prints a part of the string, because when I copy and paste that base64 into an online converter, it only shows a really tiny piece of the image. So the thing is that the string is not showing completely or somehow the base64 encoder is not working well.
Any suggestions?
From the comments, since you are using VsCode and you can't print the full string (long string)
You can use log from dart: developer,
if the string is REALLY LONG, There is a workaround to fix this, the idea is to divide your long string into small pieces (in the example, 800 length for each piece) using RegExp and then iterate into the result and print each piece.
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}

Dart base64 decoding

Here is my base64 encoded String :
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uSWQiOiJkMjNiN2ViMy03MDgyLTRkZDktOGQ0OC1lMjU2YTM3OTNiOTciLCJyZWZyZXNoVG9rZW4iOiJiN2M3MTc4Yi04OWRjLTQxMDctYjUzNC1hOGZiOTNhMzEwNzAiLCJuYW1lIjoiTGVuIiwiaWF0IjoxNTczMDI4MjU2fQ
Using https://jwt.io/ it decodes correctly
But When trying to use base64.decode('--Base64String--); in Flutter it gives me these errors
FormatException: Invalid character (at character 37)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uSWQiOiIzYWNiNzBjZS0wYzYxLT...
When removing the string in front of the . (I only need the info that comes after the .)
I get this error
FormatException: Invalid length, must be multiple of four (at character 183)
...jLTQxMDctYjUzNC1hOGZiOTNhMzEwNzAiLCJuYW1lIjoiTGVuIiwiaWF0IjoxNTczMDI4MjU2fQ
Are there any other ways of decoding base64 encoded Strings for Dart
You can use base64.normalize first.
For example:
import 'dart:convert';
void main() {
final String b64 = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uSWQiOiJkMjNiN2ViMy03MDgyLTRkZDktOGQ0OC1lMjU2YTM3OTNiOTciLCJyZWZyZXNoVG9rZW4iOiJiN2M3MTc4Yi04OWRjLTQxMDctYjUzNC1hOGZiOTNhMzEwNzAiLCJuYW1lIjoiTGVuIiwiaWF0IjoxNTczMDI4MjU2fQ';
String foo = b64.split('.')[0];
List<int> res = base64.decode(base64.normalize(foo));
print(utf8.decode(res));
}
Result:
{"alg":"HS256","typ":"JWT"}
try it. This will help you
Center(child:
Image.memory(
base64Decode(image6464.substring(23).replaceAll("\n", ""))
)
),