图像暗/光检测客户端脚本 [英] Image Dark/Light Detection Client Sided Script
问题描述
有没有人知道是否有脚本可以使用客户端脚本来检测图像(包括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 type 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 of light (true of false).
我知道有服务器端的脚本可用,但不能用于这个特定的开发。
I know there are server sided script available but cannot use that for this particular development.
提前感谢。
推荐答案
此函数将每个颜色转换为灰度并返回所有像素的平均值,因此最终值将介于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:
这篇关于图像暗/光检测客户端脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!