在flutter中将内存图像(如Uint8list)保存为图像文件

M.T*_*iri 4 dart flutter uint8array uint8list

我有一些 Uint8lists,我想将它们保存为 jpg 文件。我在网上搜索了很多,但一无所获!任何人都可以帮忙吗?

谢谢,

lsi*_*siu 8

“存储”是指写入文件吗?你真的不需要“颤振”来做到这一点。只需使用 dart 提供的库。这是下载我的gravatar的示例,您可以将其作为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);
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以保存到特定路径,例如`final dir = wait getExternalStorageDirectory(); 最终 myImagePath = dir!.path + "/myimg.png"; 文件 imageFile = 文件(myImagePath); if(!await imageFile.exists()){ imageFile.create(recursive: true); } imageFile.writeAsBytes(图像);` (2认同)
  • 请注意,这只有效,因为 Uint8List 已经以 JPEG 格式存储图像数据。因此,这个问题并没有回答如何保存 RAW 图像字节(这就是我来这里的目的),因为这些字节需要首先编码为 PNG 或 JPEG 或类似的格式。我相信这里缺少的步骤是: `ByteData byteData = wait image.toByteData(format: ImageByteFormat.png); Uint8List pngBytes = byteData.buffer.asUint8List();` 其中`image` 来自`dart:ui` 包。 (2认同)