<script> function augmentImageData(o) { o.getPixel = function (x, y) { var i = (x + y * this.width) * 4; return {R: this.data[i], G: this.data[i + 1], B: this.data[i + 2], A: this.data[i + 3]
} } o.setPixel = function (x, y, c) { var i = (x + y * this.width) * 4; this.data[i] = c.R; this.data[i + 1] = c.G; this.data[i + 2] = c.B; this.data[i + 3] = c.A; } }
function createCanvas(h, w) { var c = document.createElement("canvas"); c.width = w; c.height = h; return c; }
function draw() { var ctx = document.body.appendChild( createCanvas(400, 400)).getContext("2d"); var img = new Image(); img.onload = function () { ctx.drawImage(img, 0, 0, 400, 300); var ImDat = ctx.getImageData(0, 0, 400, 300); augmentImageData(ImDat); for (var x = 0; x < 400; x++) { for (var y = 0; y < 300; y++) { var c1 = ImDat.getPixel(x, y); var c2 = ImDat.getPixel(x, y + 3); var r = Math.abs(c1.R - c2.R) + 128; var g = Math.abs(c1.G - c2.G) + 128; var b = Math.abs(c1.B - c2.B) + 128; var grey = (r + g + b) / 3; ImDat.setPixel(x, y, {R: grey, G: grey, B: grey, A: c1.A}); } } ctx.putImageData(ImDat, 0, 0); };
img.src = "test.jpg"; } draw(); </script>
A security problem
If you try this program out you will probably find that it doesn't work. The reason is that we are loading an image from the local file system and this is a security risk. You cannot access the pixels of an image that has been loaded from a different URL and accessing pixels of a local file is particularly forbidden. If you download the file from a server with the same URL as the script then there's no problem.
To allow for testing, Chrome has a command line switch that turns off the security check - no doubt other browsers have similar features. All you have to do is locate the shortcut that you use to launch Chrome and change the target to read:
Alternatively simply use the command from the command prompt or add:
--allow-file-access-from-files
to whatever command gets Chrome.
With this command line switch it all works and you can see the result of the effect. It is also worth saying that it runs remarkably fast for a JavaScript-based image processing routine.
If you would like the code for this project then you can find it in the CodeBin.