compressImage static method
Compresses an image file with specified parameters.
Parameters:
file: The source image file to compressquality: Compression quality (0-100), default is 80maxWidth: Maximum width of the output image, default is 1920maxHeight: Maximum height of the output image, default is 1080format: Target format for the compressed imagedeleteOriginal: Whether to delete the original file after compression
Returns a File containing the compressed image.
Throws:
- ArgumentError if quality is not between 0 and 100
- FileSystemException if the file doesn't exist or is empty
- ArgumentError if the image format is unsupported
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;
}
}