changeFormatAndCompressImage static method

Future<File?> changeFormatAndCompressImage({
  1. required File image,
  2. String format = 'jpeg',
  3. required int? sizeLimit,
})

Implementation

static Future<File?> changeFormatAndCompressImage({
  required File image,
  String format = 'jpeg',
  required int? sizeLimit,
}) async {
  try {
    Uint8List? uint8list = await image.readAsBytes();

    int imageSizeInKB =
        uint8list.lengthInBytes ~/ 1024; // Calculate image size in KB
    int quality = 99; // Default initial quality
    print('imageSizeInKB:<1> $imageSizeInKB');
    bool changeImgFormat = true;
    bool isImgAffected = false;
    if (sizeLimit != null && imageSizeInKB > sizeLimit) {
      changeImgFormat = false;
      isImgAffected = true;
      CompressFormat compressFormat =
          getFormat(format) ?? CompressFormat.jpeg;
      // --> Don't remove below method. [Purpose: set image in cache to reduce compressing time]
      uint8list = await FlutterImageCompress.compressWithList(
        uint8list,
        quality: quality,
        minHeight: minHeight,
        minWidth: minWidth,
        format: compressFormat,
      );

      // --> send cache image to find the quality
      quality = await getCompressQuality(
        sizeLimit: sizeLimit,
        tempImg: uint8list,
        format: format,
      );
      // Compress the image until it reaches or is smaller than the limit
      uint8list = await FlutterImageCompress.compressWithList(
        uint8list,
        quality: quality - 1,
        minHeight: minHeight,
        minWidth: minWidth,
        format: compressFormat,
      );
    }
    if (changeImgFormat) {
      isImgAffected = true;
      CompressFormat compressFormat =
          getFormat(format) ?? CompressFormat.jpeg;
      // --> Don't remove below method. [Purpose: set image in cache to reduce compressing time]
      uint8list = await FlutterImageCompress.compressWithList(
        uint8list,
        quality: quality,
        minHeight: minHeight,
        minWidth: minWidth,
        format: compressFormat,
      );
    }
    if (!isImgAffected) {
      return image;
    } else if (uint8list.isNotEmpty) {
      File compressedImage =
          File(image.path.replaceAll(RegExp(r'\.\w+$'), '.$format'));

      await compressedImage.writeAsBytes(uint8list);

      return compressedImage;
    } else {
      print('Compression failed');
      return null;
    }
  } catch (e) {
    print('Error: $e');
    return null;
  }
}