1

I'm trying to compress image from camera or gallery, but i tried answer in this question Flutter & Firebase: Compression before upload image

But the UI was freeze , so do you guys have any solution for that, and why the image plugin meet that problem ?

UPDATE:

compressImage(imageFile).then((File file) {
   imageFile = file;
});

Future<File> compressImage(File imageFile) async {
   return compute(decodeImage, imageFile);
}

File decodeImage(File imageFile) {
   Im.Image image = Im.decodeImage(imageFile.readAsBytesSync());
   Im.Image smallerImage = Im.copyResize(
       image, 150); // choose the size here, it will maintain aspect ratio
   return new File('123.jpg')
     ..writeAsBytesSync(Im.encodeJpg(smallerImage, quality: 85));
}

I meet "unhandled exception" in this code

Petro
  • 3,484
  • 3
  • 32
  • 59
ddawng.quang
  • 101
  • 2
  • 12

1 Answers1

5

This is because compression is done in the UI thread.

You can move computation to a new thread using compute() https://docs.flutter.io/flutter/foundation/compute.html

There are currently serious limitations what a non-UI thread can do.

  • If you pass the image data, it is copied from one thread to the other, which can be slow. If you have the image in a file like you get it from image_picker it is better to pass the file path and read the image in the new thread.

  • You can only pass values that can be encoded as JSON (it's not actually encoded as JSON, but it supports the same types)

  • You can not use plugins. This means you need to move the compressed data back to the UI thread by passing the data (which again is copied) or by writing in a file and passing back the path to the file, but in this case copying might be faster because writing a file in one thread and reading it in the other is even slower). Then you can for example invoke image uploading to Firebase Cloud Storage in the UI thread, but because this is a plugin it will run in native code and not in the UI thread. It's just the UI thread that needs to pass the image along.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567