Reduce size image from bytes Uint8List

Viewed 918

I am using the file_picker package to import images before uploading them to Firebase Storage, because it allows me to choose the formats what is not possible with image_picker.

I would like to be able to reduce the size of these images to reduce their weight. The flutter_image_compress package allows to compress images but it is not available for Flutter Web.

How can I reduce the size of an image imported in Flutter Web knowing that the format is Uint8List?

2 Answers

You can use the archive package to compress any data. The following is an example function taking Uint8List and compressing it:

Uint8List compress(Uint8List input) {
  final encoder = ZLibEncoder();
  return encoder.encode(input) as Uint8List;
}

You'll want to do this in a separate isolate since this could noticeably block your UI, but this won't make any difference if your application is web-only.

if you know the image type you can convert it to jpeg and then compress it using the flutter image package.

import 'package:image/image.dart' as img;

Future<List<int>> _pngToJpg(Uint8List pngBytes) async {
  final pngImage = img.decodePng(pngBytes);
  final pngImageResized = img.copyResize(pngImage!, width: 800);
  return img.encodeJpg(pngImageResized, quality: 90);
}

you can use any other decoder depending on your image type. Expect a freeze in UI. You can use compute to minimize it.

Related