getBytes method

Uint8List getBytes({
  1. Format format = Format.rgba,
})

Get the bytes from the image. You can use this to access the color channels directly, or to pass it to something like an Html canvas context.

Specifying the format will convert the image data to the specified format. Images are stored internally in Format.rgba format; any other format will require a conversion.

For example, given an Html Canvas, you could draw this image into the canvas: Html.ImageData d = context2D.createImageData(image.width, image.height); d.data.setRange(0, image.length, image.getBytes(format: Format.rgba)); context2D.putImageData(data, 0, 0);

Implementation

Uint8List getBytes({Format format = Format.rgba}) {
  final rgba = Uint8List.view(data.buffer);
  switch (format) {
    case Format.rgba:
      return rgba;
    case Format.bgra:
      final bytes = Uint8List(width * height * 4);
      for (var i = 0, len = bytes.length; i < len; i += 4) {
        bytes[i + 0] = rgba[i + 2];
        bytes[i + 1] = rgba[i + 1];
        bytes[i + 2] = rgba[i + 0];
        bytes[i + 3] = rgba[i + 3];
      }
      return bytes;
    case Format.abgr:
      final bytes = Uint8List(width * height * 4);
      for (var i = 0, len = bytes.length; i < len; i += 4) {
        bytes[i + 0] = rgba[i + 3];
        bytes[i + 1] = rgba[i + 2];
        bytes[i + 2] = rgba[i + 1];
        bytes[i + 3] = rgba[i + 0];
      }
      return bytes;
    case Format.argb:
      final bytes = Uint8List(width * height * 4);
      for (var i = 0, len = bytes.length; i < len; i += 4) {
        bytes[i + 0] = rgba[i + 3];
        bytes[i + 1] = rgba[i + 0];
        bytes[i + 2] = rgba[i + 1];
        bytes[i + 3] = rgba[i + 2];
      }
      return bytes;
    case Format.rgb:
      final bytes = Uint8List(width * height * 3);
      for (var i = 0, j = 0, len = bytes.length; j < len; i += 4, j += 3) {
        bytes[j + 0] = rgba[i + 0];
        bytes[j + 1] = rgba[i + 1];
        bytes[j + 2] = rgba[i + 2];
      }
      return bytes;
    case Format.bgr:
      final bytes = Uint8List(width * height * 3);
      for (var i = 0, j = 0, len = bytes.length; j < len; i += 4, j += 3) {
        bytes[j + 0] = rgba[i + 2];
        bytes[j + 1] = rgba[i + 1];
        bytes[j + 2] = rgba[i + 0];
      }
      return bytes;
    case Format.luminance:
      final bytes = Uint8List(width * height);
      for (var i = 0, len = length; i < len; ++i) {
        bytes[i] = getLuminance(data[i]);
      }
      return bytes;
  }
}