saveCroppedJpeg method
Crops and saves in a JPEG file.
Returns the width and height of the cropped image. It's faster to encode as BMP and then compress to JPEG, instead of directly compressing the image to JPEG (standard flutter being slow).
Implementation
Future<(int, int)> saveCroppedJpeg() async {
final File temporaryBmpFile = File('${outputFile.path}.tmp.bmp');
Future<void> deleteTemporaryTmpFile() async {
try {
await temporaryBmpFile.delete();
} catch (e) {
// in case the file wasn't even created
}
}
final (int, int) croppedSize;
try {
croppedSize = await ImageCropper(
inputFile: inputFile,
outputFile: temporaryBmpFile,
crop: crop,
rotation: rotation,
overlayPainter: overlayPainter,
).saveCroppedBmp();
} catch (e) {
await deleteTemporaryTmpFile();
rethrow;
}
try {
// very fast: about 200ms!
final XFile? result = await FlutterImageCompress.compressAndGetFile(
temporaryBmpFile.path,
outputFile.path,
autoCorrectionAngle: false,
quality: ImagePickerConstants.imageQuality,
format: CompressFormat.jpeg,
minWidth: croppedSize.$1,
minHeight: croppedSize.$2,
);
if (result == null) {
throw Exception('Unexpected null result for JPEG compression');
}
return croppedSize;
} finally {
await deleteTemporaryTmpFile();
}
}