My code does the following:
- Picks an image with pickImage() (from image_picker package)
- Then it takes the picked image and crop it with cropImage() (image_cropper package)
After being picked, the function pickImage() saves it in this path :
/data/user/0/com.example.myapp/cache/9930cfca-6eb2.jpg
And then the cropImage() function saves the returned image here:
/data/user/0/com.example.myapp/cache/image_cropper_1924443.jpg
Here is my function
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');
}
}
Now what i want to do is to save the cropped image to a specific folder. Is there any way to implement this.
CodePudding user response:
One of the solutions is to copy the image after that cropImage() stores it in its default directory:
After getting our cropped image:
croppedImage = await ImageCropper.cropImage(...);
Do the following:
- Get the application Folder on the phone disk using the path_provider package:
final Directory dir = await getApplicationDocumentsDirectory();
final String appDir = dir.path
- Check if the file already exists, then delete it.
final File imageFile = File(appDir '/profile_picture.jpg');
if (await imageFile.exists()) {
imageFile.delete();
}
- Preferably clear the cache to avoid some problems:
imageCache!.clearLiveImages();
imageCache!.clear();
- Copy the image using the copy method which is provided by the File class:
final File copiedImage = await croppedImage.copy('$appDir/profile_picture.jpg');
- Store the new image in a variable of type File:
File myImage = File(copiedImage.path);