FLUTTER

How to compress images in Flutter?

Large images take longer to load and may result in awful user experience. Users always prefer negligible load times and don't want to see the loading indicator. Reducing image size can also reduce the monthly bills of the image storage and hosting service you are using. Image compression feature is unavoidable if you are app has a feature where the user is uploading an image. This is necessary because you cannot predict how large an image the user is going to upload.


Dart already has image compression libraries, but they are not so effective as the compression is slow and image quality is reduced significantly. Thankfully, Flutter has a package called flutter_image_compress that natively compresses the images.


Below given are the step by step tutorial on how to compress an image in Flutter using the flutter_image_compress plugin.

Install

Add flutter_image_compress to pubspec.yaml as shown in below. There are no other configurations required for the plugin on both iOS and Android operating systems.

Import

Import package at the top of the file as shown below.

Compress Image

  1. minWidth - If the image has a width smaller than the minWidth, then the size won't be changed.
  2. minHeight - If the image has a height smaller than the minHeight, then the size won't be changed. These parameters can be used so that if the image uploaded by the user is small then it won't be compressed again.
  3. quality - Defines the depth of compression. The value is between 1 to 100. For example, quality 40 results in a smaller image compared to quality 60.
  4. rotate - The angle at which the image should be rotated, if you need to rotate the image.
  5. format - The plugin supports JPG and PNG. By default it is JPG. It also supports WEBP in Android and HEIF format in iOS