cropImage method

Future<Image?> cropImage()

Crop the images based on the selected region

Implementation

Future<Image?> cropImage() async {
  if (imageEditor == null) return null;
  final ui.Image image = _imageInfo!.image;
  final Completer<Image?> imgCompleter = Completer();
  final Region region = imageEditor!.region;

  if (region.isEmpty) return null;
  if (region.width > image.width || region.height > image.height) return null;

  final ByteData? imgData = await image.toByteData();
  if (imgData == null) return null;

  const int channel = 4;
  final Uint8List resImgList =
      Uint8List(region.width * region.height * channel);
  final Uint8List oriImageList = imgData.buffer.asUint8List();

  for (int row = region.y1, idx = 0; row < region.y2; row++) {
    for (int col = region.x1; col < region.x2; col++) {
      final int rc = row * image.width * channel + col * channel;
      for (int k = 0; k < channel; k++, idx++) {
        resImgList[idx] = oriImageList[rc + k];
      }
    }
  }

  ui.decodeImageFromPixels(
      resImgList, region.width, region.height, ui.PixelFormat.rgba8888,
      (image) async {
    final ByteData? byte =
        await image.toByteData(format: ui.ImageByteFormat.png);
    imgCompleter.complete(Image.memory(byte!.buffer.asUint8List()));
  });

  return imgCompleter.future;
}