内容简介:有没有人知道是否有脚本可以使用客户端脚本来检测图像中的黑暗/亮度(包括html)?我基本上想要能够检测到背景中使用的图像类型(暗/亮),并且CSS / HTML / Jquery / JS会根据一个变暗(light of true)来适应页面.我知道有服务器端脚本可用,但不能用于这个特定的开发.
有没有人知道是否有脚本可以使用客户端脚本来检测图像中的黑暗/亮度(包括html)?
我基本上想要能够检测到背景中使用的图像类型(暗/亮),并且CSS / HTML / Jquery / JS会根据一个变暗(light of true)来适应页面.
我知道有服务器端脚本可用,但不能用于这个特定的开发.
提前致谢.
该功能将每个颜色转换为灰度级并返回所有像素的平均值,因此最终值将介于0(最暗)和255(最亮)之间)
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://stackoverflow.com/questions/13762864/image-dark-light-detection-client-sided-script
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Nature of Code
Daniel Shiffman / The Nature of Code / 2012-12-13 / GBP 19.95
How can we capture the unpredictable evolutionary and emergent properties of nature in software? How can understanding the mathematical principles behind our physical world help us to create digital w......一起来看看 《The Nature of Code》 这本书的介绍吧!