cropImageBytes function

Future<Uint8List> cropImageBytes(
  1. Uint8List source,
  2. Rect srcRect, {
  3. ImageByteFormat format = ui.ImageByteFormat.png,
})

Crop a region of an image, returning the cropped bytes.

Uses Flutter's Skia renderer — GPU-accelerated, no extra dependencies. source is the original image's encoded bytes (PNG/JPG/etc., anything instantiateImageCodec accepts). srcRect is the region to extract, in source-image pixel coordinates (use displayRectToSourceRect to convert from display-coord crop rects).

Returns encoded bytes in format (PNG by default).

Implementation

Future<Uint8List> cropImageBytes(
  Uint8List source,
  Rect srcRect, {
  ui.ImageByteFormat format = ui.ImageByteFormat.png,
}) async {
  final codec = await ui.instantiateImageCodec(source);
  final frame = await codec.getNextFrame();
  final image = frame.image;
  try {
    final width = srcRect.width.round();
    final height = srcRect.height.round();
    final recorder = ui.PictureRecorder();
    final canvas = Canvas(recorder);
    canvas.drawImageRect(
      image,
      srcRect,
      Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),
      Paint()..filterQuality = FilterQuality.high,
    );
    final picture = recorder.endRecording();
    try {
      final cropped = await picture.toImage(width, height);
      try {
        final bytes = await cropped.toByteData(format: format);
        if (bytes == null) {
          throw StateError('Cropped image returned no bytes.');
        }
        return bytes.buffer.asUint8List();
      } finally {
        cropped.dispose();
      }
    } finally {
      picture.dispose();
    }
  } finally {
    image.dispose();
  }
}