我希望能够从一张图片中获取HEX或RGB平均值,并将这个颜色设置为另一个div的背景色。
例如,如果我上传了一张红色的图片,我会得到类似于#FF0000的值。
请告诉我这是否可行 :)
非常感谢。
例如,如果我上传了一张红色的图片,我会得到类似于#FF0000的值。
请告诉我这是否可行 :)
非常感谢。
首先,在canvas
上绘制图像:
function draw(img) {
var canvas = document.createElement("canvas");
var c = canvas.getContext('2d');
c.width = canvas.width = img.width;
c.height = canvas.height = img.height;
c.clearRect(0, 0, c.width, c.height);
c.drawImage(img, 0, 0, img.width , img.height);
return c; // returns the context
}
// returns a map counting the frequency of each color
// in the image on the canvas
function getColors(c) {
var col, colors = {};
var pixels, r, g, b, a;
r = g = b = a = 0;
pixels = c.getImageData(0, 0, c.width, c.height);
for (var i = 0, data = pixels.data; i < data.length; i += 4) {
r = data[i];
g = data[i + 1];
b = data[i + 2];
a = data[i + 3]; // alpha
// skip pixels >50% transparent
if (a < (255 / 2))
continue;
col = rgbToHex(r, g, b);
if (!colors[col])
colors[col] = 0;
colors[col]++;
}
return colors;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
getColors
返回一个颜色名称和数量的映射表。透明像素将被跳过。从这个映射表中获取最常见的颜色应该很容易。
如果您真的想要每个颜色分量的平均值,您也可以从 getColors
的结果中轻松获得,但结果可能不是非常有用。 这个答案 解释了一种更好的方法。
您可以按如下方式使用它:
// nicely formats hex values
function pad(hex) {
return ("000000" + hex).slice(-6);
}
// see this example working in the fiddle below
var info = document.getElementById("info");
var img = document.getElementById("squares");
var colors = getColors(draw(img));
for (var hex in colors) {
info.innerHTML += "<li>" + pad(hex) + "->" + colors[hex];
}
查看一个工作示例。
((r << 16) | (g << 8) | b)
- Wayne只有使用canvas标签才能实现这一点,具体方法在此处描述:
http://dev.opera.com/articles/view/html-5-canvas-the-basics/#pixelbasedmanipulation
当然,这仅适用于较新的浏览器。
使用纯JavaScript从图像中获取调色板。适用于浏览器和Node环境。
计算平均颜色的步骤如下: