optimizeImage method

Future<File?> optimizeImage(
  1. File image,
  2. OptimizationConfig config
)

Implementation

Future<File?> optimizeImage(
  File image,
  OptimizationConfig config,
) async {
  try {
    final bytes = await image.readAsBytes();
    final originalImage = img.decodeImage(bytes);

    if (originalImage == null) return null;

    final optimizedPath = '${image.path}.optimized';
    List<int> optimizedBytes;

    final extension = path.extension(image.path).toLowerCase();
    switch (extension) {
      case '.jpg':
      case '.jpeg':
        optimizedBytes = _optimizeJpeg(originalImage, config);
        break;

      case '.png':
        optimizedBytes = _optimizePng(originalImage, config);
        break;

      case '.webp':
        // Use PNG encoding for WebP files since image package
        // doesn't support WebP encoding directly
        optimizedBytes = _optimizePng(originalImage, config);
        break;

      default:
        throw AssetOptException('Unsupported image type: $extension');
    }

    final optimizedFile = File(optimizedPath);
    await optimizedFile.writeAsBytes(optimizedBytes);
    return optimizedFile;
  } catch (e) {
    throw AssetOptException('Failed to optimize image ${image.path}: $e');
  }
}