我有一些 Uint8list,我想将它们保存为 jpg 文件。 有人可以帮忙吗?
“存储”是指写入文件吗?你真的不需要“颤振”来做到这一点。只需使用 dart 提供的库即可。这是下载我的头像的示例,您可以将其作为
Uin8List
获取,然后将其保存到文件中。
import 'dart:io';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
void main() {
http.get('https://www.gravatar.com/avatar/e944138e1114aefe4b08848a46465589').then((response) {
Uint8List bodyBytes = response.bodyBytes;
File('my_image.jpg').writeAsBytes(bodyBytes);
});
}
这是您问题的简单而简短的解决方案。像我一样在代码中使用这一行:
"SettableMetadata(contentType: "image/jpeg"),"
代码:
if (kIsWeb) {
await ref.putData(
await imageFile.readAsBytes(),
SettableMetadata(contentType: "image/jpeg"),
);
url = await ref.getDownloadURL();
}
第 1 步:在 pubspec.yaml 文件中添加 path_provider 包
dependencies:
path_provider: ^2.1.3
Setp 2:完成实施
Future<void> saveImage(Uint8List bytes) async {
Directory root = await getTemporaryDirectory();
String directoryPath = '${root.path}/appname';
// Create the directory if it doesn't exist
Directory(directoryPath)
.create(recursive: true)
.then((Directory directory) {
// Save the image file with a unique name based on the current timestamp
String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
String filePath = '$directoryPath/$timestamp.jpg';
// Write the image bytes to the file
File(filePath)
.writeAsBytes(bytes)
.then((File file) {
print('Image saved: $filePath');
}).catchError((error) {
print('Error saving image: $error');
});
}).catchError((error) {
print('Error creating directory: $error');
});
}