Flutter the best way to compress image

Here’s a breakdown of the potential solutions. The TLDR is that the flutter_image_compress package shrinks files much more than the ImagePicker class can itself.

Image Picker

As others have suggested, you can use the built in imaqeQuality property from ImagePicker to compress the image. This property takes a value between 0 and 100 and represents a percentage of the original image quality. The benefit to this approach is that it’s built into the image_picker package and is therefore incredibly easy to use.

  File _image;

  Future getImage() async {
    var image = await ImagePicker.pickImage(
        source: ImageSource.gallery,  
                imageQuality: 25,
    );

    setState(() {
      _image = image;
    });
  }

I did a little test to see how much various values effect the size of the image:

100% Image Quality – 4.58MB
enter image description here

50% Image Quality – 3.58MB
enter image description here

25% Image Quality – 2.61MB
enter image description here

1% Image Quality – 2.12MB
enter image description here

0% Image Quality – 3.9MB
enter image description here

In summary, you can reduce the file size of an image by more than half without much of a visible difference. Trying to force the image quality to 0% doesn’t actually shrink the file size.

flutter_image_compress
The flutter_image_compress package is fairly simple to use and it appears to be much better at actually reducing the file size.

Future<File> compressFile(File file) async {
  final filePath = file.absolute.path;

  // Create output file path
  // eg:- "Volume/VM/abcd_out.jpeg"
  final lastIndex = filePath.lastIndexOf(new RegExp(r'.jp'));
  final splitted = filePath.substring(0, (lastIndex));
  final outPath = "${splitted}_out${filePath.substring(lastIndex)}";
  var result = await FlutterImageCompress.compressAndGetFile(
    file.absolute.path, outPath,
    quality: 5,
  );

  print(file.lengthSync());
  print(result.lengthSync());

  return result;
 }

I’ll omit the images here because the all look the same:
50% Image Quality – 590KB
25% Image Quality – 276KB
5% Image Quality – 211KB

flutter_native_image
The flutter_native_image package is comparable to the flutter_image_compress package as far as file sizes go.

Future<File> compressFile(File file) async{
    File compressedFile = await FlutterNativeImage.compressImage(file.path,
        quality: 5,);
    return compressedFile;
  }

50% Image Quality – 1.02MB
25% Image Quality – 309KB
5% Image Quality – 204KB

I guess one of the benefits to this method is that you don’t need to provide it with an output pathway for the compressed file.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)