- Notifications
You must be signed in to change notification settings - Fork262
fluttercandies/flutter_image_compress
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Compresses image as native plugin (Obj-C/Kotlin). This library works on Android, iOS, macOS, Web, OpenHarmony.
- flutter_image_compress
Q:Dart already has image compression libraries. Why use native?
A:For unknown reasons, image compression in Dart language is not efficient,even in release version. Using isolate does not solve the problem.
| Feature | Android | iOS | Web | macOS | OpenHarmony |
|---|---|---|---|---|---|
| method: compressWithList | ✅ | ✅ | ✅ | ✅ | ✅ |
| method: compressAssetImage | ✅ | ✅ | ✅ | ✅ | ✅ |
| method: compressWithFile | ✅ | ✅ | ❌ | ✅ | ✅ |
| method: compressAndGetFile | ✅ | ✅ | ❌ | ✅ | ✅ |
| format: jpeg | ✅ | ✅ | ✅ | ✅ | ✅ |
| format: png | ✅ | ✅ | ✅ | ✅ | ✅ |
| format: webp | ✅ | ✅ | 🌐 | ❌ | ✅ |
| format: heic | ✅ | ✅ | ❌ | ✅ | ✅ |
| param: quality | ✅ | ✅ | 🌐 | ✅ | ✅ |
| param: rotate | ✅ | ✅ | ❌ | ✅ | ✅ |
| param: keepExif | ✅ | ✅ | ❌ | ✅ | ❌ |
dependencies:flutter_image_compress:<latest_version>
or run this command:
flutter pub add flutter_image_compress
import the package in your code:
import'package:flutter_image_compress/flutter_image_compress.dart';
Use as:
There are several ways to use the library api.
// 1. compress file and get Uint8ListFuture<Uint8List>testCompressFile(File file)async {var result=awaitFlutterImageCompress.compressWithFile( file.absolute.path, minWidth:2300, minHeight:1500, quality:94, rotate:90, );print(file.lengthSync());print(result.length);return result; }// 2. compress file and get file.Future<File>testCompressAndGetFile(File file,String targetPath)async {var result=awaitFlutterImageCompress.compressAndGetFile( file.absolute.path, targetPath, quality:88, rotate:180, );print(file.lengthSync());print(result.lengthSync());return result; }// 3. compress asset and get Uint8List.Future<Uint8List>testCompressAsset(String assetName)async {var list=awaitFlutterImageCompress.compressAssetImage( assetName, minHeight:1920, minWidth:1080, quality:96, rotate:180, );return list; }// 4. compress Uint8List and get another Uint8List.Future<Uint8List>testComporessList(Uint8List list)async {var result=awaitFlutterImageCompress.compressWithList( list, minHeight:1920, minWidth:1080, quality:96, rotate:135, );print(list.length);print(result.length);return result; }
minWidth andminHeight are constraints on image scaling.
For example, a 4000*2000 image,minWidth set to 1920,minHeight set to 1080, the calculation is as follows:
// Using dart as an example, the actual implementation is Kotlin or OC.import'dart:math'as math;voidmain() {var scale=calcScale( srcWidth:4000, srcHeight:2000, minWidth:1920, minHeight:1080, );print("scale = $scale");// scale = 1.8518518518518519print("target width = ${4000 /scale}, height = ${2000 /scale}");// target width = 2160.0, height = 1080.0}doublecalcScale({double srcWidth,double srcHeight,double minWidth,double minHeight,}) {var scaleW= srcWidth/ minWidth;var scaleH= srcHeight/ minHeight;var scale= math.max(1.0, math.min(scaleW, scaleH));return scale;}
If your image width is smaller thanminWidth or height smaller thanminHeight,scale will be 1, that is, the size will not change.
If you need to rotate the picture, use this parameter.
This property only exists in the version after 0.5.0.
And for historical reasons, there may be conflicts with rotate attributes,which need to be self-corrected.
Modify rotate to 0 or autoCorrectionAngle to false.
Quality of target image.
Ifformat is png, the param will be ignored in iOS.
Supports jpeg or png, default is jpeg.
The format class signenum CompressFormat.
Heif and webp Partially supported.
Support android by the system api (speed very nice).The library also supports iOS. However, we're usingthird-party libraries,it is not recommended due to encoding speed.In the future,libwebp by google (C/C++) may be used to do coding work,bypassing other three-party libraries, but there are no plan for that currently.
Only support iOS 11+.
UseHeifWriter for the implementation.
Only support API 28+.
And may require hardware encoder support,does not guarantee that all devicesabove API 28 are available.
The param is only support android.
For a description of this parameter, see theAndroid official website.
If this parameter is true, EXIF information is saved in the compressed result.
Attention should be paid to the following points:
- Default value is false.
- Even if set to true, the direction attribute is not included.
- Only support jpg format, PNG format does not support.
The result of returning a List collection will not have null, but will always be an empty array.
The returned file may be null. In addition, please decide for yourself whether the file exists.
You may need to convertList<int> toUint8List to display images.
To useUint8List, you need import package to your code like this:
final image=Uint8List.fromList(imageList);ImageProvider provider=MemoryImage(Uint8List.fromList(imageList));
Usage inImage Widget:
Future<Widget>_compressImage()async {List<int> image=awaittestCompressFile(file);ImageProvider provider=MemoryImage(Uint8List.fromList(image)); imageWidget=Image( image: provider??AssetImage('img/img.jpg'), );}
Write to file usage:
Future<void>writeToFile(List<int> image,String filePath) {returnFile(filePath).writeAsBytes(image, flush:true);}
Because of some support issues,all APIs will be compatible with format and system compatibility,and an exception (UnsupportedError) may be thrown,so if you insist on using webp and heic formats,please catch the exception yourself and use it on unsupported devices jpeg compression.
Example:
Future<Uint8List>compressAndTryCatch(String path)async {Uint8List result;try { result=awaitFlutterImageCompress.compressWithFile( path, format:CompressFormat.heic, ); }onUnsupportedErrorcatch (e) {print(e); result=awaitFlutterImageCompress.compressWithFile( path, format:CompressFormat.jpeg, ); }return result;}
You may need to update Kotlin to version1.5.21 or higher.
Sometimes, compressing will return null. You should check if you can read/write the file,and the parent folder of the target file must exist.
For example, use thepath_providerplugin to access some application folders,and use a permission plugin to request permission to access SD cards on Android/iOS.
Using this library, EXIF information will be removed by default.
EXIF information can be retained by setting keepExif to true,but notdirection information.
- PNG/JPEG encoder: System API.
- WebP encoder:
- SDWebImageWebPCoder on iOS.
- System API on Android.
- HEIF encoder: System API.
- HeifWriter on Android P+.
The web implementation is not required for many people,
You need change the minimum deployment target to 10.15.
Open xcode project, select Runner target, and change the value ofmacOS Deployment Target to10.15.
And, change thePodfile:Changeplatform toplatform :osx, '10.15'.
The currently supported image formats for parsing include JPEG, PNG, GIF, RAW, WebP, BMP, and SVG. However, the encoding output image formats are currently limited to JPEG, PNG, and WebP only.
当前支持的解析图片格式包括 JPEG、PNG、GIF、RAW、WebP、BMP、SVG . 编码输出图片格式当前仅支持 JPEG、PNG 和 WebP.
About
flutter image compress
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.

