-1

I am still struggiling with this annoying error. I have base64 string which I want to convert to Image. Here is the simpliest piece of code which is doing exactly what I want (at least, I saw it in different answers and code samples on the SO). I am getting the error:

Invalid character (at character 6)

my code is:

final String encodedStr = 'https://securelink.com/cameratypes/picture/13/true';
    Uint8List bytes = base64.decode(encodedStr);

and i want to disply image:

 Image.memory(bytes)
inkwelll075
  • 494
  • 4
  • 19
  • [Could this be of help to you? Seems you could use this inside your code as well](https://stackoverflow.com/questions/35940290/how-to-convert-base64-string-to-javascript-file-object-like-as-from-file-input-f) – Manaweb Feb 14 '22 at 09:16
  • You are trying to encode base64 to image right? – Ahmad Raza Feb 14 '22 at 10:01
  • @AhmadRaza yes, thats true. I think i did something completly wrong – inkwelll075 Feb 14 '22 at 10:02
  • 1
    Your code is trying to decode the string value of the URL as base64 data. As the URL is not valid base64 data, this obviously fails. You need to download the contents from the URL and decode that (which of course will only work if the URL points to valid base64 data). – l4mpi Feb 15 '22 at 11:49

2 Answers2

0

Finally, I found the solution, I don't know if it is important and will be useful to anyone who is struggling like me, but I am going to help. So, it would be easy and quick because I have already converted my image to nedeed formart (my image is base64 format), i made a dumb mistake when I was trying to convert it in String again, because it is already a String and I need Uint8List format. Side note: if your api devs said it should take a cookie or any kind of auth, it should be so.

code:

Future<String> _createFileFromString() async {
  final response = await http.get(
      Uri.parse(
        'your link here',
      ),
     headers: {
        'cookie':
            'your cookie here'
      });

  final Uint8List bytes = response.bodyBytes;
  String dir = (await getApplicationDocumentsDirectory()).path;
  String fullPath = '$dir/abc.png';
  print("local file full path ${fullPath}");
  File file = File(fullPath);
  await file.writeAsBytes(List.from(bytes));
  print(file.path);

  final result = await ImageGallerySaver.saveImage(bytes);
  print(result);

  return file.path;
}

This code saves your image in straight to the app gallery and do not display on the screen anything

inkwelll075
  • 494
  • 4
  • 19
0

If your URI that contains data after 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 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