运行以下代码:
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
void main() {
Uint8List contents = File('some.jpg').readAsBytesSync();
String encoded = base64Encode(contents);
List<int> decodedBytes = base64.decode(encoded);
String decodedString = utf8.decode(decodedBytes);
print('Decoded string: $decodedString');
}
我看到以下异常:
FormatException: Invalid UTF-8 byte (at offset 0)
#0 _Utf8Decoder.convertSingle (dart:convert-patch/convert_patch.dart:1741:7)
#1 Utf8Decoder.convert (dart:convert/utf.dart:349:37)
#2 Utf8Codec.decode (dart:convert/utf.dart:63:20)
#3 main (file:///yadda/yadda/yadda.dart:11:31)
#4 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#5 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
我不明白为什么会发生异常;我认为 base64 编码器不会生成无效的 UTF-8 字节。
ecodedBytes[0]
的值为 255
。
我愿意改变实现:长期目标是将 jpg 文件的内容硬编码到 dart 文件中,以便无需访问磁盘即可输出。
我不明白为什么在这种情况下需要将字节转换为其他格式。只需编写一个 dart 文件,并将变量分配给字节列表即可。
import 'dart:io';
import 'dart:typed_data';
void main() {
Uint8List contents = File('some.jpg').readAsBytesSync();
File output = File('lib/some.jpg.dart')..createSync();
output.writeAsStringSync('''const List<int> someJpg = $contents;''');
}
上面将创建一个 dart 文件,其中包含可用于引用图像的变量。我不知道你的确切用例是什么,但假设你想在 flutter 应用程序中将其显示为图像,那么你只需按如下方式使用它:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'some.jpg.dart';
void main() {
runApp(MaterialApp(
title: 'Image Demo',
home: Scaffold(
body: Center(
child: Image.memory(
Uint8List.fromList(someJpg),
),
),
),
));
}