如何使用 javascript 从图像中获取平均颜色或主颜色?

发布于 2024-10-20 00:16:33 字数 130 浏览 2 评论 0原文

我想要的是从图像到另一个 div 背景的这种颜色的十六进制或 RGB 平均值。

因此,如果我上传带有大量红色的图像,我会得到类似 #FF0000 的内容作为示例。

让我知道这是否可行:)

非常感谢。

what i want is to the the HEX or the RGB average value from an image to the another div background this color.

So if i upload an image with a ot of red i get something like #FF0000 just as an example.

Let Me know if this is posible :)

Many thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

爱给你人给你 2024-10-27 00:16:33

首先,在画布上绘制图像:

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];
}

请参阅工作示例

First, draw the image on a 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
}

You can now iterate over the image's pixels. A naive approach for color-detection is to simply count the frequency of each color in the image.

// 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 returns a map of color names and counts. Transparent pixels are skipped. It should be trivial to get the most-frequently seen color from this map.

If you literally want an average of each color component, you could easily get that from the results of getColors, too, but the results aren't likely to be very useful. This answer explains a much better approach.

You can use it all like this:

// 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];
}

See a working example.

无远思近则忧 2024-10-27 00:16:33
  • 将图像放在画布上。
  • 获取 2D 上下文。
  • 循环像素,并存储每个 r、g、b 值。如果发现相同,则增加一次。
  • 循环存储的 r、g、b 值并记下最大的 r、g、b 值。
  • 将 r、g、b 转换为十六进制
  • Put image on canvas.
  • Get 2D context.
  • Loop through pixels, and store each r,g,b value. If you find the same, increment it once.
  • Loop through stored r,g,b values and take note of largest r,g,b value.
  • Convert r,g,b to hex.
ㄟ。诗瑗 2024-10-27 00:16:33

这只能使用此处描述的画布标签:

http://dev.opera.com/articles/view/html-5-canvas-the-basics/#pixelbasedmanipulation

当然,这仅在较新的浏览器中可用

This is only possible using the canvas tag as described here :

http://dev.opera.com/articles/view/html-5-canvas-the-basics/#pixelbasedmanipulation

Of course this is only available in newer browsers

尹雨沫 2024-10-27 00:16:33

您可能会考虑使用 css 允许您应用的卷积过滤器。这也许能够获得您想要的效果(假设您想将其呈现回 html 中)。所以你可以显示图像两次,一次是卷积的。

话虽如此,如果您出于某种目的自己需要这些信息,那么这并不起作用。

You might consider using the convolution filters css allows you to apply. This might be able to get the effect you're going for ( assuming you're wanting to present it back into the html). So you could display the image twice , one convolved.

That being said, doesn't really work if you need the information yourself for some purpose.

迎风吟唱 2024-10-27 00:16:33

2023 年更新:有一个 javascript 库可以做到这一点:
颜色小偷 - https://lokeshdhakar.com/projects/color-thief /

仅使用 Javascript 从图像中获取调色板。工作于
浏览器和 Node 中。

Update 2023: There is a javascript lib to do just that:
Color Thief - https://lokeshdhakar.com/projects/color-thief/

Grab the color palette from an image using just Javascript. Works in
the browser and in Node.

柏林苍穹下 2024-10-27 00:16:33

要找到平均颜色:

  1. 将图像放在画布上
  2. 将图像大小调整为 1px x 1px
  3. 获取结果像素的颜色(该像素将是计算出的平均值)

For finding that average color:

  1. Put Image on Canvas
  2. Resize image to 1px by 1px
  3. Get the color of the resulting pixel(This pixel will be the calculated average)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文