InputImage.fromBitmap constructor

InputImage.fromBitmap({
  1. required Uint8List bitmap,
  2. required int width,
  3. required int height,
  4. int rotation = 0,
})

Creates an instance of InputImage from bitmap data.

This constructor is designed to work with bitmap data from Flutter UI components such as those obtained from ui.Image.toByteData(format: ui.ImageByteFormat.rawRgba).

Example usage with a RepaintBoundary:

// Get the RenderObject from a GlobalKey
final boundary = myKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
// Capture the widget as an image
final image = await boundary.toImage();
// Get the raw RGBA bytes
final byteData = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
// Create the InputImage
final inputImage = InputImage.fromBitmap(
  bitmap: byteData!.buffer.asUint8List(),
  width: image.width,
  height: image.height,
);

bitmap should be the raw bitmap data, typically from ui.Image.toByteData(). width and height are the dimensions of the bitmap. rotation is optional and defaults to 0. It is only used on Android.

Implementation

factory InputImage.fromBitmap({
  required Uint8List bitmap,
  required int width,
  required int height,
  int rotation = 0,
}) {
  return InputImage._(
    bitmapData: bitmap,
    type: InputImageType.bitmap,
    rotation: rotation,
    metadata: InputImageMetadata(
      size: Size(width.toDouble(), height.toDouble()),
      rotation: InputImageRotation.values.firstWhere(
        (element) => element.rawValue == rotation,
        orElse: () => InputImageRotation.rotation0deg,
      ),
      // Assuming BGRA format from Flutter UI
      format: InputImageFormat.bgra8888,
      bytesPerRow: width * 4, // 4 bytes per pixel (RGBA)
    ),
  );
}