decodePng method

PuzzleArtwork decodePng(
  1. Uint8List bytes, {
  2. bool isForeground(
    1. int argb
    )?,
})

Decodes PNG cells; fully opaque non-white pixels are foreground by default. Supply isForeground to use opaque white ink or a different artwork mask.

Implementation

PuzzleArtwork decodePng(
  Uint8List bytes, {
  bool Function(int argb)? isForeground,
}) {
  final source = image.decodePng(bytes);
  if (source == null) throw const FormatException('Invalid PNG image.');
  final decoded = source.convert(format: image.Format.uint8, numChannels: 4);
  final colors = [const PaletteColor('background', 0xFFFFFFFF)];
  final ids = <int, int>{};
  final cells = <int>[];
  for (var r = 0; r < decoded.height; r++) {
    for (var c = 0; c < decoded.width; c++) {
      final pixel = decoded.getPixel(c, r);
      final argb =
          pixel.a.toInt() * 16777216 +
          pixel.r.toInt() * 65536 +
          pixel.g.toInt() * 256 +
          pixel.b.toInt();
      final foreground =
          isForeground?.call(argb) ??
          (pixel.a.toInt() == 255 && argb != 0xFFFFFFFF);
      if (!foreground) {
        cells.add(0);
        continue;
      }
      cells.add(
        ids.putIfAbsent(argb, () {
          colors.add(
            PaletteColor(
              'color-${argb.toRadixString(16).padLeft(8, '0')}',
              argb,
            ),
          );
          return colors.length - 1;
        }),
      );
    }
  }
  return PuzzleArtwork(
    SolutionGrid(width: decoded.width, height: decoded.height, cells: cells),
    Palette(colors),
    sourcePng: bytes,
  );
}