compressImage method

Future<String> compressImage(
  1. String filePath, {
  2. int? quality,
})

Compress image to WebP (spec: quality 85, 40–80% reduction). Returns compressed path, or original if compression fails.

Implementation

Future<String> compressImage(String filePath,
    {int? quality}) async {
  try {
    final file = File(filePath);
    if (!await file.exists()) return filePath;

    final tempDir = await getTemporaryDirectory();
    final targetPath =
        '${tempDir.path}/cm_${DateTime.now().millisecondsSinceEpoch}.webp';

    final result =
        await FlutterImageCompress.compressAndGetFile(
      filePath,
      targetPath,
      quality: quality ?? config.imageQuality,
      format: CompressFormat.webp,
    );

    if (result == null) {
      return filePath;
    }

    final orig = await file.length();
    final comp = await result.length();
    final pct =
        ((1 - comp / orig) * 100).toStringAsFixed(1);
    CloudLogger.debug(
        'Compressed: ${_fmt(orig)} → ${_fmt(comp)} ($pct% reduction)');

    return result.path;
  } catch (e, st) {
    CloudLogger.error(
        'Compression failed, using original',
        error: e,
        stackTrace: st);
    return filePath;
  }
}