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

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();

Related

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

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

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 can I convert a utf8 string to LATIN1 in Dart?

I have many strings where the accents are converted wrongfully. I take those Strings from an API, so I cannot get them in other encoding formats. As an example, the string é returns as é from the API. Is there any way I can convert these strings to show the accents correctly?
Well, you can try something like this:
import 'dart:convert';
void main() {
const input = 'é';
final output = utf8.decode(latin1.encode(input), allowMalformed: true);
print(output); // é
}
Alternative you can get the response from your web call as bytes by using bodyBytes on the response object:
https://pub.dev/documentation/http/latest/http/Response/bodyBytes.html
And parse it with: latin1.decode or whatever charset the server are sending the the data as.

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

Flutter - Character encoding is not behaving as expected

I am parsing a local JSON file that has words containing rarely used special characters in Icelandic.
When displaying the characters I get mixed up symbols but not the characters, for some others I just get a square instead of a symbol.
I am using this type of encoding "\u00c3"
Update: Example of the characters I am using: þ, æ, ý, ð
Q: What is the best way to display those kind of characters and avoid any chance of display failures?
Update #2:
How I am parsing:
Future<Null> getAll() async{
var response = await
DefaultAssetBundle.of(context).loadString('assets/json/dictionary.json');
var decodedData = json.decode(response);
setState(() {
for(Map word in decodedData){
mWordsList.add(Words.fromJson(word));
}
});
}
The class:
class Words{
final int id;
final String wordEn, wordIsl;
Words({this.id, this.wordEn, this.wordIsl});
factory Words.fromJson(Map<String, dynamic> json){
return new Words(
id: json['wordId'],
wordEn: json['englishWord'],
wordIsl: json['icelandicWord']
);
}
}
JSON Model:
{
"wordId": 47,
"englishWord": "Age",
//Here's a String that has two special characters
"icelandicWord": "\u00c3\u00a6vi"
}
I had similar issues with accented characters. They were not displayed as expected.
This worked for me
final codeUnits = source.codeUnits;
return Utf8Decoder().convert(codeUnits);
The problem is that your JSON is stored locally.
Let's say you have
Map<String, String> jsonObject = {"info": "Æ æ æ Ö ö ö"};
So to show your text correctly you have to encode and decode back your JSON with utf-8.
I understand that's serialization and deserialization are costly operations, but's it's a workaround for locally stored JSON objects that contains UTF-8 texts.
import 'dart:convert';
jsonDecode(jsonEncode(jsonObject))["info"]
If you get that JSON from server, then it's much more simpler, for example in dio package you can chose contentType params that's is "application/json; charset=utf-8" by default.