averageLuminanceOfRegion function

double? averageLuminanceOfRegion({
  1. required Uint8List rgba,
  2. required int width,
  3. required int height,
  4. required Rect pixelRect,
  5. required Color background,
})

Average WCAG relative luminance of rgba (a rawRgba-format image buffer, width×height) within pixelRect (in pixel coordinates of that buffer). Fully transparent pixels (alpha < 0.02) are evaluated as background instead of their own (meaningless) color, mirroring how a viewer would actually perceive them. Returns null if pixelRect doesn't cover any pixel.

Implementation

double? averageLuminanceOfRegion({
  required Uint8List rgba,
  required int width,
  required int height,
  required Rect pixelRect,
  required Color background,
}) {
  if (width <= 0 || height <= 0) return null;
  final x0 = pixelRect.left.floor().clamp(0, width - 1);
  final x1 = pixelRect.right.ceil().clamp(x0 + 1, width);
  final y0 = pixelRect.top.floor().clamp(0, height - 1);
  final y1 = pixelRect.bottom.ceil().clamp(y0 + 1, height);

  var sumR = 0.0, sumG = 0.0, sumB = 0.0;
  var n = 0;
  for (var y = y0; y < y1; y++) {
    for (var x = x0; x < x1; x++) {
      final i = (y * width + x) * 4;
      final a = rgba[i + 3] / 255.0;
      if (a < 0.02) {
        sumR += background.r;
        sumG += background.g;
        sumB += background.b;
      } else {
        sumR += rgba[i] / 255.0;
        sumG += rgba[i + 1] / 255.0;
        sumB += rgba[i + 2] / 255.0;
      }
      n++;
    }
  }
  if (n == 0) return null;
  return wcagLuminance(sumR / n, sumG / n, sumB / n);
}