簡體   English   中英

Base 64 轉換為 Image 並得到錯誤 Invalid character (at character 6)

[英]Base 64 convert to Image and get the error Invalid character (at character 6)

我仍在為這個煩人的錯誤而苦苦掙扎。 我有 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 格式),當我試圖再次將它轉換為字符串時,我犯了一個愚蠢的錯誤,因為它已經是一個字符串,我需要 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;
}

此代碼將您的圖像直接保存到應用程序庫中,並且不會在屏幕上顯示任何內容

如果您的 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

Vean este post, me ayudo a resolver el problema, es mas bien por que el Image.memory no reconoce el byte sino el ascii

Flutter 將字節轉換為字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM