如何使用getImageData()计算图像颜色?
我想得到并显示计数。
客户将图像上传到我的网站
我将网站上的图像保存为" T-Shirt"
但我不能用超过10种颜色打印图像
我想在下载到我的电脑之前检查网站上的任何图像。
答案 0 :(得分:2)
这是计算独特颜色的方法:
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);
&#13;
<canvas></canvas><br><output></output>
&#13;
您现在可以使用统计信息(键数)查找唯一数量的颜色,然后您可以通过查找近似值来减少数字 - 或使用 ColorThief 来完成整个为你工作。