当您在 Flutter 中以字节形式接收图像时,如何 read/write 具有原始扩展名的图像文件?

How do I read/write image file with its original extension when you receive the image as bytes in Flutter?

这是我遇到的问题:

我的用户可以从 Facebook(jpeg 或 gif)或本地设备(可以是 png、jpg 或其他)设置他们的个人资料图片。

我通过以下方式从 Facebook 获取图像:

// Get the name, email and picture
final graphResponse = await http.get(
        'https://graph.facebook.com/v4.0/me?fields=name,email,picture.width(300).height(300)&access_token=$token');

// Decode JSON
final profile = jsonDecode(graphResponse.body);
final String stringData = profile['picture']['data'];
final bytes = Uint8List.fromList(stringData.codeUnits);

并通过以下方式从本地设备获取图像:

final imagePicker = ImagePicker();

// Call image picker
final pickedFile = await imagePicker.getImage(
      source: ImageSource.gallery,
      maxWidth: MAX_WIDTH_PROFILE_IMAGE,
  );

final imageBytes = await pickedFile.readAsBytes();

那我这里得到的都是字节(Uint8List),怎么按原来的扩展名保存呢?

那么稍后我如何在不检查其扩展名的情况下再次阅读它们?

例如:

// Setting the filename
// Could be jpg or png or bmp or gif. 
// How to determine the extension?
final filename = 'myProfileImage'; 

// Getting App's local directory
final Directory localRootDirectory =
          await getApplicationDocumentsDirectory();
final String filePath = p.join(localRootDirectory.path, path, filename);

final file = File(filePath);

你看,在读取文件时我们需要指定完整的文件名。但是如何确定扩展名呢?

您可以通过不在文件名中设置扩展名来完全避免处理扩展名。扩展名仅用于指示 可能 包含在 OS 文件中的内容,但它们不是必需的,在您的情况下也不需要,尤其是因为您知道自己有该文件中的某种图像数据,您的应用程序可能是唯一使用该文件的东西。

但是,如果您真的想在文件名中使用扩展名,您可以将 image package. This provides a Decoder abstract class 与多个实现者一起使用,以实现各种图像编码方法。要确定您的文件使用了哪种方法,您可以检查您需要的每种可能的解码器类型的 isValidFile 并相应地编写扩展名。

示例:

PngDecoder png = PngDecoder();
if(png.isValidFile(data //Uint8List inputted here)) {
  print("This file is a PNG");
}