compress function
Compress image file input synchronously
On Flutter, you can run this compression on background using isolates with
ImageFileConfiguration param;
var compressedImage = await compute(compress, param);
Implementation
ImageFile compress(ImageFileConfiguration param) {
final input = param.input;
if (input.contentType == 'image/webp') return input;
final config = param.config;
final image = img.decodeImage(input.rawBytes);
if (image != null) {
List<int>? output;
switch (config.outputType) {
case OutputType.jpg:
output = img.encodeJpg(image, quality: config.jpgQuality);
break;
case OutputType.png:
output = img.encodePng(image, level: config.pngCompression.level);
break;
}
return ImageFile(
filePath: '',
rawBytes: Uint8List.fromList(output),
width: image.width,
height: image.height,
);
} else {
final animation = img.decodeGif(input.rawBytes);
if (animation != null) {
final output = img.encodeGif(
animation,
samplingFactor: config.animationGifSamplingFactor,
);
return ImageFile(
filePath: '',
rawBytes: Uint8List.fromList(output),
width: animation.width,
height: animation.height,
);
}
}
return input;
}