Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Image 当您以字节的形式接收图像时,如何读取/写入图像文件及其原始扩展名?_Image_File_Flutter_Io - Fatal编程技术网

Image 当您以字节的形式接收图像时,如何读取/写入图像文件及其原始扩展名?

Image 当您以字节的形式接收图像时,如何读取/写入图像文件及其原始扩展名?,image,file,flutter,io,Image,File,Flutter,Io,我的问题是: 我的用户可以从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)&a

我的问题是:

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

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

只要不在文件名中设置扩展名,就可以完全避免处理扩展名。扩展名的存在只是为了指示操作系统文件中可能包含的内容,但它们不是必需的,在您的情况下也不需要,特别是因为您知道该文件中有某种图像数据,并且您的应用程序可能是唯一使用该文件的程序

但是,如果确实希望在文件名中使用扩展名,则可以使用。这为各种图像编码方法提供了一个具有多个实现者的解决方案。要确定文件使用了哪种方法,可以使用所需的每种可能的解码器类型的
isValidFile
进行检查,并相应地编写扩展名

例如:

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