cropImage function

Future<String?> cropImage(
  1. String src, {
  2. required int x,
  3. required int y,
  4. required int w,
  5. required int h,
  6. Future<ProcessResult> run(
    1. String,
    2. List<String>
    ) = boundedRun,
})

Crops src to the pixel rect x,y,w,h into a new PNG, null when no tool could; sips ignores a crop that ends on the bottom edge, so that one stops a row short.

Implementation

Future<String?> cropImage(
  String src, {
  required int x,
  required int y,
  required int w,
  required int h,
  Future<ProcessResult> Function(String, List<String>) run = boundedRun,
}) async {
  final dst = '${src.replaceAll(RegExp(r'\.png$'), '')}-crop-$x-$y-${w}x$h.png';
  final full = pngSize(src);
  final rows = Platform.isMacOS && full != null && y + h >= full.$2 && h > 1 ? h - 1 : h;
  try {
    final r = Platform.isMacOS
        ? await _runImageTool(run, 'sips', ['-c', '$rows', '$w', '--cropOffset', '$y', '$x', src, '--out', dst])
        : await _runImageTool(run, 'convert', [src, '-crop', '${w}x$h+$x+$y', '+repage', dst]);
    return r.exitCode == 0 && File(dst).existsSync() ? dst : null;
  } on Object {
    return null;
  }
}