How to Use Web Workers for Image Manipulation
Today I’d like to talk about picture manipulation in HTML5, using pure Javascript.
The Test Case
The test application is simple. On the left a picture to manipulate and on the right the updated result (a sepia tone effect is applied):
The page itself is simple and is described as follow:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>PictureWorker</title> <link href="default.css" rel="stylesheet" /> </head> <body id="root"> <div id="sourceDiv"> <img id="source" src="mop.jpg" /> </div> <div id="targetDiv"> <canvas id="target"></canvas> </div> <div id="log"></div> </body> </html>
The overall process to apply a sepia tone effect requires you to compute a new RGB value for every pixel of the existing source picture, and then render it on the <canvas> tag with id=”target”. Below are the formulae we use to create the new RGB values from the existing RGB values of a pixel:
finalRed= (red * 0.393) + (green * 0.769) + (blue * 0.189);
finalGreen = (red * 0.349) + (green * 0.686) + (blue * 0.168);
finalBlue= (red * 0.272) + (green * 0.534) + (blue * 0.131);
To make it a bit more realistic, I’ve added a bit of randomness to my sepia formulae. I create a noise value which ranges from 0.5 to 1, which determines the degree to which my final pixel output matches the RGB value calculated via the formulae above, versus the degree to which it retains it’s original RGB values.