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

16

我有一些Uint8lists,想将它们保存为jpg文件。有人可以帮忙吗?


dart.io 中的 File 类有保存列表的方法。 - pskink
我不想保存这个列表。 - M.Taha Basiri
“我想把它们保存在存储中” - 那么你实际上想做什么? - pskink
抱歉解释不清楚!现在已经修改了。 - M.Taha Basiri
问题很难理解。请更好地解释你的问题。 - Cem Kaan
现在能理解了吗?! - M.Taha Basiri
2个回答

23

你所说的“存储”是指写入文件吗?其实你不需要使用“flutter”来做这件事,只需使用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);
  });
}

1
'my_image.jpg',它将被存储在哪里?我们如何设置特定的文件夹来存储该文件? - djalmafreestyler
2
你可以将文件保存到指定路径,如下所示:final dir = await getExternalStorageDirectory(); final myImagePath = dir!.path + "/myimg.png"; File imageFile = File(myImagePath); if(! await imageFile.exists()){ imageFile.create(recursive: true); } imageFile.writeAsBytes(image); - Maseed
@djalmafreestyler - 它将被存储在您运行程序的“当前工作目录”。 - lsiu
2
请注意,这仅适用于Uint8List已经以JPEG格式存储图像数据的情况。因此,该问题没有回答如何保存原始图像字节(这就是我来到这里的原因),因为这些字节需要首先编码为PNG或JPEG或类似格式。我认为这里缺少的步骤是: ByteData byteData = await image.toByteData(format: ImageByteFormat.png); Uint8List pngBytes = byteData.buffer.asUint8List(); 其中image来自dart:ui包。 - LZM

2

以下是您问题的简单而短小的解决方案。像我一样在您的代码中使用这行:

"SettableMetadata(contentType: "image/jpeg")," 

代码:

 if (kIsWeb) {
         await ref.putData(
          await imageFile.readAsBytes(),
           SettableMetadata(contentType: "image/jpeg"),
         );
         url = await ref.getDownloadURL();
         }

1
你的解决方案引发了另一个问题,什么是ref? - mamena tech

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接