【问题标题】:How to save a cropped image with cropImage() to a specific folder in Flutter如何使用cropImage() 将裁剪后的图像保存到Flutter 中的特定文件夹
【发布时间】:2021-11-23 02:39:21
【问题描述】:

我的代码执行以下操作:

  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');
    }
  }

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

【问题讨论】:

    标签: image flutter directory crop


    【解决方案1】:

    其中一种解决方案是复制图像,然后 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 类提供的复制方法复制图像:
    final File copiedImage = await croppedImage.copy('$appDir/profile_picture.jpg');
    
    1. 将新图像存储在 File 类型的变量中:
    File myImage = File(copiedImage.path);
    

    【讨论】:

      猜你喜欢
      • 2012-11-12
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 2015-10-23
      • 2021-07-20
      • 2018-01-07
      • 2018-07-30
      • 1970-01-01
      相关资源
      最近更新 更多