计算特定区域的平均图像颜色

3
我发布了一个问题,但我没有能够很好地解释它(设置字体颜色通过获取图像平均颜色),并且stackoverflow不允许我上传超过一个链接,所以我将尝试再次解释问题。如果我犯了任何错误,请原谅,我是新来的。实际上,我想从图像中特定区域取出平均颜色。我已经看到了许多计算整个图像平均颜色的示例。

这是图片

在这里,我有两个文本框。文本框1的颜色将基于其背景颜色(云颜色平均值)而不是整个图像的平均值。同样,底部的文本框2的颜色应该只是其背景颜色的平均值(公路颜色)。


你是如何将文本添加到图像中的?使用Canvas吗?在计算平均值之前,图像上会有文本吗? - lemieuxster
我可以使用画布,但有没有更高效的解决方案?@lemieuxster - user3754676
我猜我在问你是如何将文本添加到图像中的。你的示例只显示了一张图片 - 它会是一张图片还是带有HTML元素的图片? - lemieuxster
该插件分析给定DIV后面图像的平均颜色,然后根据平均颜色的亮度阈值应用特定的CSS类。可能它不完全符合您的需求,但以间接的方式实现了您所追求的目标。 - Luca Detomi
1个回答

1
感谢我得到了答案。特别感谢@Cinn帮助我解决了问题。如果有人想要查找图像中特定区域的平均颜色,请访问JsFiddle链接。
var average_color_background = function(image, title) {
    var treat_properties = function(elmt_propertie) {
        return parseInt(elmt_propertie.replace(/px/, ''));
    }
    var image_width = treat_properties(getComputedStyle(image, null).width),
        image_height = treat_properties(getComputedStyle(image, null).height),
        title_width = treat_properties(getComputedStyle(title, null).width),
        title_height = treat_properties(getComputedStyle(title, null).height),
        title_top = treat_properties(getComputedStyle(title, null).top),
        title_left = treat_properties(getComputedStyle(title, null).left);

    var c = document.createElement('canvas');
        c.width = image_width;
        c.height = image_height;
        c.style.position = "absolute";
        c.style.top = 0;
        c.style.left = 0;
        c.style.zIndex = 0; // invisible calculation

    document.getElementsByTagName('body')[0].appendChild(c);

    var ctx = c.getContext("2d");

    var image_bis = new Image();
    image_bis.crossOrigin = 'anonymous'; // avoid security error

    image_bis.onload = function(){
        ctx.drawImage(image_bis,0,0,image_width,image_height);
        var imageData = ctx.getImageData(title_left, title_top, title_width, title_height),
            mapPixel = imageData.data;

        var red = 0,
            green = 0,
            blue = 0,
            length = 4 * title_width * title_height;
        for(var i=0;i<length;i+=4) {
            red += mapPixel[i];
            green += mapPixel[i+1];
            blue += mapPixel[i+2];
        }
        length = length / 4;
        red = Math.round(red/length);
        green = Math.round(green/length);
        blue = Math.round(blue/length);

        // display result, can easily be improved for something more beautiful (e.g. using complementary color) :
        title.style.backgroundColor = 'rgb('+red+','+green+','+blue+')';

        c.parentNode.removeChild(c);
        return true;        
    }
    image_bis.src = image.src;
}
average_color_background(document.getElementById('image'),document.getElementById('h1'));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接