saveCroppedBmp method

Future<(int, int)> saveCroppedBmp()

Crops and saves in a BMP file.

Returns the width and height of the cropped image. As BMP for much quicker results.

Here we don't use isolates, as it's not compatible with dart:ui, cf. https://github.com/flutter/flutter/issues/115030#issuecomment-1314242954

Implementation

Future<(int, int)> saveCroppedBmp() async {
  ui.Image? cropped;
  try {
    cropped = await _getCroppedImage();

    final ByteData? rawData = await cropped.toByteData(
      format: ui.ImageByteFormat.rawRgba,
    );
    if (rawData == null) {
      throw Exception('Cannot convert file');
    }

    final int croppedWidth = cropped.width;
    final int croppedHeight = cropped.height;

    cropped.dispose();
    cropped = null;

    final image.Image rawImage = await _convertImageFromUI(
      rawData,
      croppedWidth,
      croppedHeight,
    );
    // TODO(monsieurtanuki): optim - here we generate the full data, then print it. Stream it instead?
    await outputFile.writeAsBytes(image.encodeBmp(rawImage), flush: true);
    return (croppedWidth, croppedHeight);
  } finally {
    cropped?.dispose();
  }
}