compressImage static method

Future<File> compressImage({
  1. required File file,
  2. int quality = 80,
  3. int maxWidth = 1920,
  4. int maxHeight = 1080,
  5. ImageFormat? format,
  6. bool deleteOriginal = false,
})

Compresses an image file with specified parameters.

Parameters:

  • file: The source image file to compress
  • quality: Compression quality (0-100), default is 80
  • maxWidth: Maximum width of the output image, default is 1920
  • maxHeight: Maximum height of the output image, default is 1080
  • format: Target format for the compressed image
  • deleteOriginal: Whether to delete the original file after compression

Returns a File containing the compressed image.

Throws:

Implementation

static Future<File> compressImage({
  required File file,
  int quality = 80,
  int maxWidth = 1920,
  int maxHeight = 1080,
  ImageFormat? format,
  bool deleteOriginal = false,
}) async {
  if (quality < 0 || quality > 100) {
    throw ArgumentError('Quality must be between 0 and 100');
  }

  if (!await file.exists()) {
    throw FileSystemException('File does not exist', file.path);
  }

  final fileSize = await file.length();
  if (fileSize == 0) {
    throw FileSystemException('File is empty', file.path);
  }

  final extension = path.extension(file.path).toLowerCase();
  if (!['.jpg', '.jpeg', '.png', '.webp'].contains(extension)) {
    throw ArgumentError('Unsupported image format: $extension');
  }

  try {
    format ??= _getImageFormatFromExtension(extension);

    final tempDir = await getTemporaryDirectory();
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    final tempFile =
        File(path.join(tempDir.path, 'temp_${timestamp}${extension}'));
    await file.copy(tempFile.path);

    final output = await FlutterImageCompress.compressWithFile(tempFile.path,
        quality: quality,
        minWidth: maxWidth,
        minHeight: maxHeight,
        format: format == ImageFormat.png
            ? CompressFormat.png
            : format == ImageFormat.webp
                ? CompressFormat.webp
                : CompressFormat.jpeg);

    await tempFile.delete();

    if (output == null || output.isEmpty) {
      throw Exception('Compression failed: output file is empty');
    }

    final outputExtension = _getExtensionFromFormat(format);
    final outputPath =
        path.join(tempDir.path, 'compressed_$timestamp$outputExtension');

    final outputFile = File(outputPath);
    await outputFile.writeAsBytes(output);

    if (deleteOriginal && await file.exists()) {
      await file.delete();
    }

    return outputFile;
  } catch (e) {
    if (kDebugMode) {
      print('Error compressing image: $e');
    }
    rethrow;
  }
}