如何获得使用JavaScript的图像的平均或主要颜色? [英] How to get the average or main color from an image with javascript?

查看:110
本文介绍了如何获得使用JavaScript的图像的平均或主要颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 :)

非常感谢。

推荐答案

首先,在画布上绘制图片

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 颜色名称和计数的地图。将跳过透明像素。从这张地图中获得最常见的颜色应该是微不足道的。

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.

如果你真的想要每个颜色组件的平均可以很容易地从 getColors 的结果中得到结果,但结果不太可能非常有用。 此回答解释了一种更好的方法。

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.

你可以这样使用:

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

查看工作示例

这篇关于如何获得使用JavaScript的图像的平均或主要颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆