📜  如何使用图像选择器将图像保存到应用程序目录 - 无论代码示例

📅  最后修改于: 2022-03-11 14:56:38.084000             🧑  作者: Mango

代码示例1
...
File _storedImage;
...

void _takePicture() async {
  // 1. Create an ImagePicker instance.
  final ImagePicker _picker = ImagePicker();

  // 2. Use the new method.
  //
  // getImage now returns a PickedFile instead of a File (form dart:io)
  final PickedFile pickedImage = await _picker.getImage(...)

  // 3. Check if an image has been picked or take with the camera.
  if (pickedImage == null) {
    return;
  }

  // 4. Create a File from PickedFile so you can save the file locally
  // This is a new/additional step.
  File tmpFile = File(pickedFile.path);

  // 5. Get the path to the apps directory so we can save the file to it.
  final String path = await getApplicationDocumentsDirectory().path;
  final String fileName = basename(pickedFile.path); // Filename without extension
  final String fileExtension = extension(pickedFile.path); // e.g. '.jpg'

  // 6. Save the file by copying it to the new location on the device.
  tmpFile = await tmpFile.copy('$path/$fileName$fileExtension');

  // 7. Optionally, if you want to display the taken picture we need to update the state
  // Note: Copying and awaiting the file needs to be done outside the setState function.
  setState(() => _storedImage = tmpFile);
}