webImageData function

JSObject webImageData(
  1. MpImage image
)

Converts an immutable MpImage into browser ImageData.

Browser image sources are eight-bit RGBA. Higher precision formats are deterministically converted to that representation at this boundary.

Implementation

JSObject webImageData(MpImage image) {
  final Uint8ClampedList rgba = Uint8ClampedList(image.width * image.height * 4);
  final int pixelCount = image.width * image.height;

  // Resolve the storage subtype once per image rather than once per pixel.
  switch (image) {
    case MpImageUint8(:final format, :final data):
      for (
        int pixel = 0, input = 0, output = 0;
        pixel < pixelCount;
        pixel += 1, input += format.channels, output += 4
      ) {
        _writeUint8Pixel(rgba, output, data, input, format);
      }
    case MpImageUint16(:final format, :final data):
      for (
        int pixel = 0, input = 0, output = 0;
        pixel < pixelCount;
        pixel += 1, input += format.channels, output += 4
      ) {
        _writeUint16Pixel(rgba, output, data, input, format);
      }
    case MpImageFloat32(:final format, :final data):
      for (
        int pixel = 0, input = 0, output = 0;
        pixel < pixelCount;
        pixel += 1, input += format.channels, output += 4
      ) {
        _writeFloatPixel(rgba, output, data, input, format);
      }
  }

  final JSAny? constructor = globalContext['ImageData'];

  if (constructor == null || !constructor.isA<JSFunction>()) {
    throw const MpException(MpStatus.unavailable, 'This browser does not expose ImageData.');
  }
  return (constructor as JSFunction).callAsConstructor<JSObject>(
    rgba.toJS,
    image.width.toJS,
    image.height.toJS,
  );
}