-->

How to count Color on Image using HTML canvas getI

2020-08-01 05:52发布

问题:

How to using getImageData() to count color on image?
I want to get and show number of count.

What I mean about "Counting Color" ?

The Customer upload an image to my website.
And I save an image from website for print to "T-Shirt".
But I can't print image with over 10 colors.
I want to check any images on website before download to my computer.

回答1:

Here's a way to count unique colors:

  • Iterate buffer
  • Create an object to hold key for each color
  • Increment the key

var canvas = document.querySelector("canvas"),
    out = document.querySelector("output"),
    ctx = canvas.getContext("2d"),
    w = canvas.width,
    h = canvas.height,
    cells = 9, sx = w / cells, sy = h / cells, x, y

// random color boxes (will be pretty even in count):
for(y = 0; y < h; y += sy) {for(x = 0; x < w; x += sx) {
  ctx.fillStyle = "hsl(" + (360*Math.random()) + ",60%,50%)";
  ctx.fillRect(x|0, y|0, Math.ceil(sx), Math.ceil(sy));
}}

// get bitmap
var idata = ctx.getImageData(0, 0, w, h),            // area to analyze
    buffer32 = new Uint32Array(idata.data.buffer),   // use 32-bit buffer (faster)
    i, len = buffer32.length,
    stats = {};

for(i = 0; i < len; i++) {
  var key = "" + (buffer32[i] & 0xffffff);           // filter away alpha channel
  if (!stats[key]) stats[key] = 0;                   // init this color key
  stats[key]++                                       // count it..
}

// you can loop through the keys and convert the key into RGB values later
out.innerHTML = JSON.stringify(stats);

// convert first key:
var keys = Object.keys(stats),
    count = keys.length,
    key = keys[0]
var r = key & 0xff, g = (key & 0xff00)>>>8, b = (key & 0xff0000)>>>16;
alert("First key: " + r + "," + g + "," + b + "=" + stats[key] + 
      "\nUnique colors: " + count);
<canvas></canvas><br><output></output>

You can now use the statistics (number of keys) to find unique number of colors, then you can reduce the numbers by finding close values - or use ColorThief to do the whole job for you.