getImageCompressed method

Future<void> getImageCompressed(
  1. XFile imageFile,
  2. String type
)

Compresses the given image file.

imageFile is the image file to be compressed.

Implementation

Future<void> getImageCompressed(XFile imageFile, String type) async {
  final filePath = imageFile.path;
  var imgExtension = filePath.split(".").last;
  final splitted = filePath.split(".").first;
  final outPath = "${splitted}_out.$imgExtension";

  XFile? imageCompressed = await FlutterImageCompress.compressAndGetFile(
    filePath,
    outPath,
    rotate: 0,
    quality: 70,
    format: imgExtension.toLowerCase() == "png"
        ? CompressFormat.png
        : CompressFormat.jpeg,
  );

  if (imageCompressed != null) {
    File file = File(imageCompressed.path);
    int sizeBytes = file.lengthSync();
    double sizeMb = sizeBytes / (1024 * 1024);
    callback.success(
      fileData: ReturnModel(
        filePath: imageCompressed.path,
        fileName: imageCompressed.path.split('/').last,
        fileExtension: getFileExtension(imageCompressed.path),
        size: sizeMb,
      ),
      type: type,
    );
  } else {
    callback.error('Image compression failed');
  }
}