首页 > 解决方案 > 如何使用cropImage() 将裁剪后的图像保存到Flutter 中的特定文件夹

问题描述

我的代码执行以下操作:

  1. 使用pickImage()选择图像(来自 image_picker 包)
  2. 然后它获取拾取的图像并使用cropImage()(image_cropper 包)对其进行裁剪

被选中后,函数pickImage()将其保存在此路径中:

/data/user/0/com.example.myapp/cache/9930cfca-6eb2.jpg

然后cropImage()函数将返回的图像保存在这里:

/data/user/0/com.example.myapp/cache/image_cropper_1924443.jpg

这是我的功能

  Future pickImage(source) async {
    try {
      final pickedFile = await ImagePicker().pickImage(source: source);
      if (pickedFile == null) return;

      File? croppedImage = await ImageCropper.cropImage(
          sourcePath: pickedFile.path,
          aspectRatio: CropAspectRatio(ratioX: 1.0, ratioY: 1.0)
      );
      if(croppedImage == null) return;

      this.image = File(croppedImage.path);
      setState((){});
     } on PlatformException catch (e) {
      print('Failed to catch image: $e');
    }
  }

现在我想做的是将裁剪后的图像保存到特定文件夹中。有没有办法实现这一点。

标签: imageflutterdirectorycrop

解决方案


一种解决方案是在cropImage()将图像存储在其默认目录中之后复制图像:

得到我们裁剪的图像后:

croppedImage = await ImageCropper.cropImage(...);

请执行下列操作:

  1. 使用path_provider包获取手机磁盘上的应用文件夹:
final Directory dir = await getApplicationDocumentsDirectory();
final String appDir = dir.path
  1. 检查文件是否已经存在,然后将其删除。
final File imageFile = File(appDir + '/profile_picture.jpg');
if (await imageFile.exists()) {
  imageFile.delete();
}
  1. 最好清除缓存以避免一些问题:
imageCache!.clearLiveImages();
imageCache!.clear();
  1. 使用File类提供的 copy 方法复制图像:
final File copiedImage = await croppedImage.copy('$appDir/profile_picture.jpg');
  1. 将新图像存储在File类型的变量中:
File myImage = File(copiedImage.path);

推荐阅读