Created
April 14, 2014 22:10
-
-
Save rlemon/10686312 to your computer and use it in GitHub Desktop.
getLuminance function - lum.js
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
// pass it an image resource (new Image() or HTMLImageElemenet) and it will | |
// return average lum over the image or given bounds between 0-255 | |
function getLuminance(imgResource, /* following is optional */x1, y1, x2, y2) { | |
// create canvas and set the height/width to the image | |
var canvas = document.createElement('canvas'), | |
context = canvas.getContext('2d'), | |
height = canvas.height = imgResource.height, | |
width = canvas.width = imgResource.width, | |
// holding for the data, and average lum | |
idata, data, lum = 0; | |
// draw image then get image data back. if they specify a bounds only get that. | |
context.drawImage(imgResource, 0, 0, width, height); | |
idata = context.getImageData(x1||0, y1||0, x2||width, y2||height); | |
/// show the viewing area---- | |
//context.rect(x1||0, y1||0, x2||width, y2||height); | |
//context.stroke(); | |
//imgResource.parentNode.appendChild(canvas); | |
///-------------------------- | |
data = idata.data; | |
// loop over the image matrix | |
for (var i = 0; i < data.length; i += 4) { | |
// http://en.wikipedia.org/wiki/Luminance_(relative) | |
lum += ((data[i] * 0.2126) + (data[i + 1] * 0.7152) + (data[i + 2] * 0.0722)); | |
} | |
// average it and return | |
lum /= data.length * 0.25; | |
return lum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment