compressImage static method

Future<XFile> compressImage(
  1. XFile source,
  2. int quality, {
  3. dynamic imageSizeCallBack(
    1. Size
    )?,
  4. bool fromGallery = false,
})

Implementation

static Future<XFile> compressImage(
  XFile source,
  int quality, {
  Function(Size)? imageSizeCallBack,
  bool fromGallery = false,
}) async {
  File sourceFile = File(source.path);
  try {
    img.Image? input = await img.decodeJpgFile(source.path);
    // rotate image if android because camera image is landscape
    if (input == null) {
      return source;
    }
    if (Platform.isAndroid && !fromGallery) {
      input = img.copyRotate(input, angle: -90);
    }
    int imageWidth = input.width;
    int imageHeight = input.height;
    input = img.copyResize(
      input,
      width: imageWidth > imageHeight ? 1920 : 1080,
      height: imageWidth > imageHeight ? 1080 : 1920,
      maintainAspect: true,
    );
    final dirPath = (await getTemporaryDirectory()).path;
    final imagePath = '$dirPath/${basename(source.path)}';
    var compressedXFile = XFile.fromData(
      img.encodeJpg(input, quality: quality),
      path: imagePath,
    );
    await compressedXFile.saveTo(imagePath);
    var fileLength = await compressedXFile.length();
    // Nếu vẫn lớn hơn 2MB thì giảm chất lượng ảnh
    if (fileLength > 2000000) {
      return await compressImage(compressedXFile, 90);
    }
    // var compressedSize = await _calculateImageSize(compressedFile);
    logger.i(
      'Resize successfully: ${sourceFile.readAsBytesSync().lengthInBytes / 1000000}MB to ${fileLength / 1000000}MB',
    );
    logger.i(
      'Resize successfully:${imageWidth}x$imageHeight => ${input.width}x${input.height}',
    );
    imageSizeCallBack?.call(
      Size(input.width.toDouble(), input.height.toDouble()),
    );
    return compressedXFile;
  } catch (e) {
    return source;
  }
}