Flutter Image Compress: A Comprehensive Guide

Published on by Flutter News Hub

Flutter Image Compress: A Comprehensive Guide

Flutter Image Compress is a native plugin that allows for efficient image compression on Android, iOS, macOS, Web, and OpenHarmony. This guide provides a comprehensive overview of the library, its features, usage, and troubleshooting tips.

Why Use Native Compression?

Dart's built-in image compression capabilities are not as efficient as native implementations, even in release mode. Using Flutter Image Compress leverages native libraries (Obj-C/Kotlin) for optimal performance.

Platform Features

Feature Android iOS Web macOS OpenHarmony
compressWithList
compressAssetImage
compressWithFile
compressAndGetFile
format: jpeg
format: png
format: webp 🌐
format: heic
param: quality 🌐
param: rotate
param: keepExif

🌐: Browser support varies.

Usage

1. Add dependency to pubspec.yaml:

dependencies:
  flutter_image_compress: ^latest_version

2. Import the package:

import 'package:flutter_image_compress/flutter_image_compress.dart';

3. Compress using different methods:

  • compressWithList: Compress a list of bytes.
  • compressAssetImage: Compress an asset image.
  • compressWithFile: Compress an image file.
  • compressAndGetFile: Compress an image file and save it to a new file.

Example:

// Compress an image file
File file = File('/path/to/image.jpg');
Uint8List result = await FlutterImageCompress.compressWithFile(file.absolute.path, minWidth: 1920, minHeight: 1080, quality: 96, rotate: 180);

// Compress an asset image
Uint8List assetList = await FlutterImageCompress.compressAssetImage(
  'assets/image.png',
  minHeight: 1920,
  minWidth: 1080,
  quality: 96,
  rotate: 180,
);

About Common Params

minWidth and minHeight: Constraints on image scaling.

rotate: Rotate the image by the specified angle.

quality: Quality of the resulting image. Ignored for PNG format on iOS.

format: Supports JPEG, PNG, WebP, and HEIF (experimental).

inSampleSize: Selects a subset of the pixels in the image, reducing its size. Only supported on Android.

keepExif: Retains EXIF information in the compressed image.

Result

The result of compression is a list of bytes or a file. Empty arrays or null files indicate a successful compression.

Runtime Error

Unsupported formats may cause an UnsupportedError. Catch this error and handle it by using a compatible format.

Android

Update Kotlin to version 1.5.21 or higher for optimal functionality.

Troubleshooting

Compressing returns null: Ensure you have read/write access to the file and that its parent folder exists.

About EXIF Information

EXIF information is removed by default. Set keepExif to true to retain it (except for direction information).

Web

Add the following script to your index.html file:


macOS

Change the macOS Deployment Target to 10.15 in the XCode project and Podfile.

OpenHarmony

Encode output image formats are limited to JPEG, PNG, and WebP.

Flutter News Hub