In my Flutter application, I'm trying to crop image in background using compute()
method, because if I try to perform this task on main thread, UI will freeze for many seconds.
This is my method to process image:
Future<Uint8List> processImage(Uint8List bytes) async {
img_lib.Image? image = img_lib.decodeImage(bytes);
if (image != null) {
double targetAspectRatio = 2 / 3;
int cropWidth = image.width;
int cropHeight = (image.width * targetAspectRatio).toInt();
if (cropHeight > image.height) {
cropHeight = image.height;
cropWidth = image.height ~/ targetAspectRatio;
}
int cropX = (image.width - cropWidth) ~/ 2;
int cropY = (image.height - cropHeight) ~/ 2;
img_lib.Image croppedImage = img_lib.copyCrop(
image,
x: cropX,
y: cropY,
width: cropWidth,
height: cropHeight
);
List<int> compressedBytes = img_lib.encodeJpg(croppedImage, quality: 60);
bytes = Uint8List.fromList(compressedBytes);
}
return bytes;}
This is my method to select image and call method processImage()
in compute()
:
Future<void> _selectMedia() async {
final picker = ImagePicker();
final pickedFile = await picker.pickMedia();
Uint8List bytes = await pickedFile.readAsBytes();
bytes = await compute(processImage, bytes);
}
Now, when method _selectMedia()
is called on button click, I got this error:
E/flutter (17096): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Invalid argument(s): Illegal argument in isolate message: object is unsendable - Library:'dart:async' Class: _AsyncCompleter@4048458 (see restrictions listed at SendPort.send() documentation for more information)
Do someone know what is the problem, and how can I fix it?