0

[Flutter] How do I crop the image based on the overlay on top of Camera function?

I set the image to this:

final image = await _controller.takePicture();

I want to crop the image based on the rectangle overlay.

currently I assign the model to:

model.img = image.path;

but instead of the image, I want to crop it first, then assign to the cropped image path.

1 Answers1

0

For this you can use copyCrop function. Here is an example

import 'dart:ui' as ui;
import 'package:image/image.dart' as img;

final double left = ...;
final double top = ...;
final double width = ...;
final double height = ...;

final bytes = File(image.path).readAsBytesSync();
final rawImage = img.decodeImage(bytes);

final pictureRecorder = ui.PictureRecorder();
final canvas = Canvas(pictureRecorder);
final paint = Paint();
canvas.drawImage(imgCodec, Offset.zero, paint);

final croppedImage = img.copyCrop(
  rawImage,
  left.toInt(),
  top.toInt(),
  width.toInt(),
  height.toInt(),
);

final croppedBytes = img.encodePng(croppedImage);

final croppedImageFile = await saveImageToDisk(croppedBytes);
model.img = croppedImageFile.path;

In the above code, replace ... with your actual values for the cropping rectangle.

Shashank Deepak
  • 163
  • 1
  • 8