0

如何在背景图像中找到重复次数最多的像素并找出颜色?帮助!

4

1 回答 1

0

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

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

在这里,我创建了一个示例。这将加载 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";
于 2013-06-22T20:31:36.893 回答