flutter Base 64转换为Image并得到错误无效字符(在字符6处)

kfgdxczn  于 2022-12-19  发布在  Flutter
关注(0)|答案(2)|浏览(233)

我还在纠结这个恼人的错误。我有base64字符串,我想转换为图像。这里是最简单的代码,这是做什么,正是我想要的(至少,我看到它在不同的答案和代码样本的SO)。我得到的错误:

Invalid character (at character 6)

我的密码是:

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

我想显示图像:

Image.memory(bytes)
b4lqfgs4

b4lqfgs41#

最后,我找到了解决方案,我不知道它是否重要,是否对像我这样挣扎的人有用,但我会帮助他们。所以,这将是简单和快速的,因为我已经把我的图像转换成了nedeed formart(我的图像是base64格式),我犯了一个愚蠢的错误,当我试图将它转换为字符串再次,因为它已经是一个字符串,我需要Uint8List格式。边注:如果您API开发人员说它应该接受cookie或任何类型的身份验证,那么它应该接受。
代码:

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;
}

这段代码直接将您的图像保存到应用程序库中,并且不会在屏幕上显示任何内容

kokeuurv

kokeuurv2#

如果您的URI包含RFC-2397中定义的逗号后的数据,Dart的URI类基于RFC-3986,因此您不能使用它。请用逗号分隔字符串并取其最后一部分:

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

参考:https://stackoverflow.com/a/59015116/12382178

相关问题