Last active
February 23, 2017 19:20
-
-
Save nickkos101/8d94d8da0e71afe951306efc866bf847 to your computer and use it in GitHub Desktop.
Using Canvas get the value of an images total brightness.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getImageBrightness(imageSrc) { | |
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; | |
} | |
return Math.floor(colorSum / (this.width*this.height)); | |
} | |
return img.onload(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment