【问题标题】:Base 64 convert to Image and get the error Invalid character (at character 6)Base 64 转换为 Image 并得到错误 Invalid character (at character 6)
【发布时间】:2022-02-15 21:15:15
【问题描述】:

我仍在为这个恼人的错误而苦苦挣扎。我有想要转换为 Image 的 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)

【问题讨论】:

  • 您正在尝试将 base64 编码为图像对吗?
  • @AhmadRaza 是的,这是真的。我认为我做错了什么
  • 您的代码正在尝试将 URL 的字符串值解码为 base64 数据。由于 URL 不是有效的 base64 数据,这显然失败了。您需要从 URL 下载内容并对其进行解码(当然,这只有在 URL 指向有效的 base64 数据时才有效)。

标签: flutter dart base64url


【解决方案1】:

最后,我找到了解决方案,我不知道它是否重要并且对像我一样苦苦挣扎的人有用,但我会提供帮助。所以,这将是简单快捷,因为我已经将我的图像转换为需要的格式(我的图像是 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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2020-09-12
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    相关资源
    最近更新 更多