encodeImage method

  1. @override
Uint8List encodeImage(
  1. Image image,
  2. GifEncodeOptions options
)
override

Encodes input to raster bytes, with the given options or default options.

Implementation

@override
Uint8List encodeImage(Image image, GifEncodeOptions options) {
  if (image.width > 0xffff || image.height > 0xffff) {
    throw const ImageCodecException(
      'GIF dimensions may not exceed 65535 pixels',
    );
  }
  final _IndexedColorImage indexed = _quantizeIndexedColor(image, options);
  final int tableSize = _tableSize(indexed.paletteLength);
  final int tableBits = tableSize.bitLength - 1;
  final OutputBuffer output = OutputBuffer()
    ..writeBytes(_signature)
    ..writeUint16(image.width)
    ..writeUint16(image.height)
    ..writeByte(0x80 | 0x70 | (tableBits - 1))
    ..writeByte(0)
    ..writeByte(0);
  _writeColorTable(output, indexed.palette, tableSize);
  if (indexed.transparentIndex case final int transparentIndex) {
    output
      ..writeByte(0x21)
      ..writeByte(0xf9)
      ..writeByte(4)
      ..writeByte(1)
      ..writeUint16(0)
      ..writeByte(transparentIndex)
      ..writeByte(0);
  }
  output
    ..writeByte(0x2c)
    ..writeUint16(0)
    ..writeUint16(0)
    ..writeUint16(image.width)
    ..writeUint16(image.height)
    ..writeByte(0);
  final int minimumCodeSize = tableBits < 2 ? 2 : tableBits;
  output.writeByte(minimumCodeSize);
  final Uint8List compressed = _GifLzwEncoder.encode(
    indexed.indices,
    minimumCodeSize: minimumCodeSize,
  );
  int offset = 0;
  while (offset < compressed.length) {
    final int length = compressed.length - offset > 255 ? 255 : compressed.length - offset;
    output
      ..writeByte(length)
      ..writeBytes(Uint8List.sublistView(compressed, offset, offset + length));
    offset += length;
  }
  output
    ..writeByte(0)
    ..writeByte(0x3b);
  return output.takeBytes();
}