Search code examples
flutterimage-compression

Compress image to specific size in Flutter App


is there any way to compress image based on the image size? I want the output to be 100 to 200 KB for any input image for my Flutter app.

I tried using flutter_image_compress but it compresses based on quality not on size.


Solution

  • Quality == Size

    with this you determine your image in uint8list

    Future<Uint8List> testCompressFile(File file, int quality) async {
        var result = await FlutterImageCompress.compressWithFile(
          file.absolute.path,
          minWidth: 2300,
          minHeight: 1500,
          quality: 100 - quality,
          rotate: 90,
        );
        print(file.lengthSync());
        print(result.length);
        return result;
      }
    

    this will print the size in bytes

    print(uint8ListImage.lengthInBytes);
    

    if the image exceeds 200 kB, you call up the function to the right size (quality)

    Future<Uint8List> compressImageToLower200kB(File file){
     for( int i = 0 ; i<100 ; i ++ ) {
    Uint8List imageCompressed = await testCompressFile(file, i);
      if(imageCompressed.lengthInBytes <200000){
    return imageCompressed;
     }
    }