客户端脚本中的图像亮度检测 [英] Image brightness detection in client side script

查看:64
本文介绍了客户端脚本中的图像亮度检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道是否存在使用客户端脚本来检测图像(包括HTML)中的暗度/亮度的脚本?

Does anyone know if there is a script available to detect darkness/lightness in an image (HTML included) using a client sided script?

我基本上希望能够检测背景中使用的图像(暗/亮)的亮度,并让CSS/HTML/jQuery/JS根据暗或亮(真或假)的变量来调整页面).

I basically want to be able to detect the brightness of image (dark/light) used in the background and have CSS/HTML/jQuery/JS adapt the page based on a variable that is either dark or light (true or false).

我知道有可用的服务器端脚本,但不能用于特定的开发项目.

I know there are server-side scripts available but cannot use that for this particular development project.

推荐答案

此函数会将每种颜色转换为灰度并返回所有像素的平均值,因此最终值将在0(最暗)到255(最亮)之间

This function will convert each color to gray scale and return average of all pixels, so final value will be between 0 (darkest) and 255 (brightest)

function getImageLightness(imageSrc,callback) {
    var img = document.createElement("img");
    img.src = imageSrc;
    img.style.display = "none";
    document.body.appendChild(img);

    var colorSum = 0;

    img.onload = function() {
        // create canvas
        var canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this,0,0);

        var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
        var data = imageData.data;
        var r,g,b,avg;

        for(var x = 0, len = data.length; x < len; x+=4) {
            r = data[x];
            g = data[x+1];
            b = data[x+2];

            avg = Math.floor((r+g+b)/3);
            colorSum += avg;
        }

        var brightness = Math.floor(colorSum / (this.width*this.height));
        callback(brightness);
    }
}

用法:

getImageLightness("image.jpg",function(brightness){
    console.log(brightness);
});

JSFiddle:

http://jsfiddle.net/s7Wx2/

这篇关于客户端脚本中的图像亮度检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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