【问题标题】:How do I read/write image file with its original extension when you receive the image as bytes in Flutter?当您在 Flutter 中以字节形式接收图像时,如何读取/写入具有原始扩展名的图像文件?
【发布时间】:2020-10-29 13:19:54
【问题描述】:

这是我遇到的问题:

我的用户可以从 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);

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

【问题讨论】:

    标签: image file flutter io


    【解决方案1】:

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

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

    例子:

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

    【讨论】:

      猜你喜欢
      • 2012-05-03
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      相关资源
      最近更新 更多