image - 如何使用cropImage() 将裁剪后的图像保存到Flutter 中的特定文件夹
问题描述
我的代码执行以下操作:
- 使用pickImage()选择图像(来自 image_picker 包)
- 然后它获取拾取的图像并使用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');
}
}
现在我想做的是将裁剪后的图像保存到特定文件夹中。有没有办法实现这一点。
解决方案
一种解决方案是在cropImage()将图像存储在其默认目录中之后复制图像:
得到我们裁剪的图像后:
croppedImage = await ImageCropper.cropImage(...);
请执行下列操作:
- 使用path_provider包获取手机磁盘上的应用文件夹:
final Directory dir = await getApplicationDocumentsDirectory();
final String appDir = dir.path
- 检查文件是否已经存在,然后将其删除。
final File imageFile = File(appDir + '/profile_picture.jpg');
if (await imageFile.exists()) {
imageFile.delete();
}
- 最好清除缓存以避免一些问题:
imageCache!.clearLiveImages();
imageCache!.clear();
- 使用File类提供的 copy 方法复制图像:
final File copiedImage = await croppedImage.copy('$appDir/profile_picture.jpg');
- 将新图像存储在File类型的变量中:
File myImage = File(copiedImage.path);
推荐阅读
- android - Android Studio 使用 gradle 同步构建配置问题
- sql - 如何计算两个表之间的指标
- mysql - MySQL从许多表中返回唯一组合
- electron - Electron 应用程序在 Windows 10 中运行良好,但在 Windows 7 中显示白屏
- c# - WPF CoerceCallback 取消值更改
- telegram - Github Actions:缺少电报令牌或用户列表
- angular - 如何强制 navigateByUrl() 在 Angular 9 中导航域根目录?
- c - 将用于查找最低有效设置位的 ASM 函数移植到 C 中
- python - 计算不同时间间隔的 RMSE
- java - Android:将 Checkbox 对象转换为应用一组规则的数组