Javascript - 大多数重复背景图像上的像素

时间:2013-06-22 19:29:00

标签: javascript image pixels

如何在背景图像中找到最重复的像素并找出颜色? 救命啊!

1 个答案:

答案 0 :(得分:0)

您无法通过JavaScript访问背景图片的像素数据。您需要做的是创建一个新的Image对象并将源设置为背景图像URL。之后,您将必须执行以下步骤:

  • 创建内存中的画布对象
  • 在画布上绘制图像
  • 获取图像数据,遍历所有像素并将颜色存储在对象中(key = color,value = repitition of amount)
  • 按照重复次数对数组进行排序,然后选择第一个值

在这里,我创建了一个例子。这会加载JSconf徽标并将正文的背景颜色设置为最重复的颜色。

// Create the image
var image = new Image();
image.crossOrigin = "Anonymous";

image.onload = function () {
    var w = image.width, h = image.height;

    // Initialize the in-memory canvas
    var canvas = document.createElement("canvas");
    canvas.width = w;
    canvas.height = h;

    // Get the drawing context
    var context = canvas.getContext("2d");

    // Draw the image to (0,0)
    context.drawImage(image, 0, 0);

    // Get the context's image data
    var imageData = context.getImageData(0, 0, w, h).data;

    // Iterate over the pixels
    var colors = [];
    for(var x = 0; x < w; x++) {
        for(var y = 0; y < h; y++) {
            // Every pixel has 4 color values: r, g, b, a
            var index = ((y * w) + x) * 4;

            // Extract the colors
            var r = imageData[index];
            var g = imageData[index + 1];
            var b = imageData[index + 2];

            // Turn rgb into hex so we can use it as a key
            var hex = b | (g << 8) | (r << 16);

            if(!colors[hex]) {
                colors[hex] = 1;
            } else {
                colors[hex] ++;   
            }
        }
    }

    // Transform into a two-dimensional array so we can better sort it
    var _colors = [];
    for(var color in colors) {
        _colors.push([color, colors[color]]);   
    }

    // Sort the array
    _colors.sort(function (a, b) {
        return b[1] - a[1]; 
    });

    var dominantColorHex = parseInt(_colors[0][0]).toString(16);
    document.getElementsByTagName("body")[0].style.backgroundColor = "#" + dominantColorHex;
};

image.src = "http://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/JavaScript-logo.png/600px-JavaScript-logo.png";