Created
March 6, 2012 07:44
-
-
Save 1999/1984747 to your computer and use it in GitHub Desktop.
HTML5 grayscale images
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 grayscale(src) { | |
var canvas = document.createElement("canvas"), | |
ctx = canvas.getContext("2d"), | |
imgPixels, x, y, i, avg; | |
var imgObj = new Image(); | |
imgObj.src = src; | |
canvas.width = imgObj.width; | |
canvas.height = imgObj.height; | |
ctx.drawImage(imgObj, 0, 0); | |
imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height); | |
for(y = 0; y < imgPixels.height; y++) { | |
for(x = 0; x < imgPixels.width; x++) { | |
i = (y * 4) * imgPixels.width + x * 4; | |
avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3; | |
imgPixels.data[i] = avg; | |
imgPixels.data[i + 1] = avg; | |
imgPixels.data[i + 2] = avg; | |
} | |
} | |
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height); | |
return canvas.toDataURL(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment