expectImage function

void expectImage(
  1. String path,
  2. Uint8List rgba, {
  3. required int width,
  4. required int height,
  5. bool? bless,
  6. String failures = 'build/fynkel_failures',
})

Checks rgba (RGBA8, rows top to bottom, width × height) against the PNG at path, a picture saved before. Two pictures are the same when no channel differs by more than 2/255 (4/255 near black, where a GPU's dither moves it), but for at most 1 pixel in 1000: what passes from one Mac or GPU to another.

When they differ, it saves the picture and one of the difference (brighter is further) in failures as <name>.actual.png and <name>.diff.png, and throws an ImageDiffers saying how much.

bless (or FYNKEL_BLESS=1 in the environment, as in FYNKEL_BLESS=1 flutter test) saves rgba at path instead: to make the picture the first time, or when a change to it is meant. Look at it before keeping it.

Implementation

void expectImage(
  String path,
  Uint8List rgba, {
  required int width,
  required int height,
  bool? bless,
  String failures = 'build/fynkel_failures',
}) {
  if (rgba.length != width * height * 4) {
    throw ArgumentError.value(rgba.length, 'rgba', 'is not $width × $height RGBA8 (${width * height * 4} bytes)');
  }
  final file = File(path);
  if (bless ?? Platform.environment['FYNKEL_BLESS'] == '1') {
    file.parent.createSync(recursive: true);
    file.writeAsBytesSync(encodePng(width, height, rgba));
    return;
  }
  if (!file.existsSync()) {
    throw ImageDiffers('there is no picture at $path yet: run the test with FYNKEL_BLESS=1 to save this one');
  }
  final saved = decodePng(file.readAsBytesSync());
  if ((saved.width, saved.height) != (width, height)) {
    throw ImageDiffers('$path is ${saved.width} × ${saved.height}, this picture $width × $height');
  }
  final expected = saved.rgba;
  var off = 0, worst = 0;
  final diff = Uint8List(rgba.length);
  for (var i = 0; i < rgba.length; i += 4) {
    var d = 0, over = false;
    for (var c = 0; c < 4; c++) {
      final e = (rgba[i + c] - expected[i + c]).abs();
      if (e > d) d = e;
      if (e > (rgba[i + c] <= 48 && expected[i + c] <= 48 ? 4 : 2)) over = true;
    }
    if (d > worst) worst = d;
    if (over) off++;
    diff
      ..[i] = (d * 16).clamp(0, 255)
      ..[i + 3] = 255;
  }
  if (off * 1000 <= width * height) return;
  final name = file.uri.pathSegments.last.replaceFirst(RegExp(r'\.png$'), '');
  final out = Directory(failures)..createSync(recursive: true);
  File('${out.path}/$name.actual.png').writeAsBytesSync(encodePng(width, height, rgba));
  File('${out.path}/$name.diff.png').writeAsBytesSync(encodePng(width, height, diff));
  throw ImageDiffers(
    '$path: $off of ${width * height} pixels differ by more than 2/255 (4 near black), the worst by $worst; '
    'this picture and the difference are in ${out.path}',
  );
}