cropImage static method

Future<Uint8List?> cropImage({
  1. required CameraImage cameraImage,
  2. required Rect cropRect,
  3. int rotation = 0,
  4. bool flipHorizontal = false,
})

Implementation

static Future<Uint8List?> cropImage({
  required CameraImage cameraImage,
  required Rect cropRect,
  int rotation = 0,
  bool flipHorizontal = false,
}) async {
  try {
    final imageBytes = await captureFrameAsPng(
      cameraImage: cameraImage,
      rotation: rotation,
      flipHorizontal: flipHorizontal,
    );

    if (imageBytes == null) {
      log('Failed to convert camera image to PNG');
      return null;
    }

    // Decode the image
    img.Image? originalImage = img.decodeImage(imageBytes);

    if (originalImage == null) {
      log('Failed to decode image');
      return imageBytes;
    }

    // Ensure crop rect is within image bounds
    final int cropX = cropRect.left.toInt().clamp(0, originalImage.width - 1);
    final int cropY = cropRect.top.toInt().clamp(0, originalImage.height - 1);
    final int cropWidth = cropRect.width.toInt().clamp(1, originalImage.width - cropX);
    final int cropHeight = cropRect.height.toInt().clamp(1, originalImage.height - cropY);

    // Validate crop dimensions
    if (cropWidth <= 0 || cropHeight <= 0) {
      log('Invalid crop dimensions');
      return imageBytes;
    }

    // Crop the image
    img.Image croppedImage = img.copyCrop(
      originalImage,
      x: cropX,
      y: cropY,
      width: cropWidth,
      height: cropHeight,
    );

    // Encode back to bytes
    return Uint8List.fromList(img.encodePng(croppedImage));
  } catch (e) {
    log('Error cropping image: $e');
    return null;
  }
}