Created
June 17, 2011 14:46
-
-
Save kkaefer/1031558 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 alphaImageLuminosity(el) { | |
if (!HTMLCanvasElement || !el.complete) return -1; | |
var canvas = document.createElement('canvas'); | |
canvas.setAttribute('width', el.width); | |
canvas.setAttribute('height', el.height); | |
var c = canvas.getContext('2d'); | |
c.drawImage(el, 0, 0); | |
var r = 0, g = 0, b = 0, total = 0; | |
var pixels = c.getImageData(0, 0, el.width, el.height).data; | |
// Look at every pixel's alpha value and only proceed if it is semi-transparent. | |
for (var i = 3; i < pixels.length; i += 4) { | |
if (pixels[i] < 255 && pixels[i] > 0) { | |
total++; | |
r += pixels[i - 3]; | |
g += pixels[i - 2]; | |
b += pixels[i - 1]; | |
} | |
} | |
if (!total) return 0; | |
// Calculate average luminosity of all alpha pixels. | |
// Using the median of all per-pixel luminosities would be better but is | |
// computationally much more expensive and since this runs in the UI thread, | |
// is not an option at this point. | |
return Math.pow(r / total / 255, 2.2) * 0.2126 + | |
Math.pow(g / total / 255, 2.2) * 0.7152 + | |
Math.pow(b / total / 255, 2.2) * 0.0722; | |
} | |
im.onload = function() { | |
console.warn(alphaImageLuminosity(im)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment