Getting average color of the image

Benchmark created on


Description

This test results will probably be skewed by the browser caching image data to GPU memory or elsewhere.

Preparation HTML

<img 
  crossorigin="anonymous"
  alt=""
  src="https://images.unsplash.com/photo-1680925697894-106c453c6e9c"
/>


Setup

function getAverageColor(ctx) {
  var width = ctx.canvas.width;
  var height = ctx.canvas.height;
  
  var imageData = ctx.getImageData(0, 0, width, height);
  var data = imageData.data;

  var r = 0;
  var g = 0;
  var b = 0;
  var count = 0;

  for (var i = 0, l = data.length; i < l; i += 4) {
    r += data[i];
    g += data[i+1];
    b += data[i+2];
  }

  count = data.length / 4;
  r = ~~(r / count);
  g = ~~(g / count);
  b = ~~(b / count);

  return { r: r, g: g, b: b };
}

// Test could be flawed.
// It looks like browser is good at caching things
// that we draw over and over again onto different
// canvases, some runs will perform in under 1ms

const img = document.getElementsByTagName('img')[0];

Test runner

Ready to run.

Testing in
TestOps/sec
Resize to 1x1px and read that pixel's color
const canvas = document.createElement('canvas');
const width = canvas.width = 1;
const height = canvas.height = 1;
const ctx = canvas.getContext('2d');

ctx.drawImage(img, 0, 0, 1, 1);

const p = ctx.getImageData(0, 0, 1, 1).data; 
const avg = { r: p[0], g: p[1], b: p[2] };

// results.push(avg);
ready
Resize to 16x16px and calculate arithmetic average
const canvas = document.createElement('canvas');
const width = canvas.width = 16;
const height = canvas.height = 16;
const ctx = canvas.getContext('2d');

ctx.drawImage(img, 0, 0, width, height);

const avg = getAverageColor(ctx);

// results.push(avg);
ready
Process image in its natural size and get arithmetic average
const canvas = document.createElement('canvas');
const width = canvas.width = img.width;
const height = canvas.height = img.height;
const ctx = canvas.getContext('2d');

ctx.drawImage(img, 0, 0, width, height);

const avg = getAverageColor(ctx);

// results.push(avg);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.