The following code converts image colors to grayscale.
This recipe must be ran on a web server due to security constraints with the getImageData() method.
<!DOCTYPE HTML> <html> <head> <script> window.onload = function(){ let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); /*from w w w . j ava 2 s. c o m*/ let imageObj = new Image(); imageObj.onload = function(){ let sourceWidth = this.width; let sourceHeight = this.height; let destX = canvas.width / 2 - sourceWidth / 2; let destY = canvas.height / 2 - sourceHeight / 2; let sourceX = destX; let sourceY = destY; context.drawImage(this, destX, destY); let imageData = context.getImageData(sourceX, sourceY, sourceWidth, sourceHeight); let data = imageData.data; for (let i = 0; i < data.length; i += 4) { let brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; data[i] = brightness; // red data[i + 1] = brightness; // green data[i + 2] = brightness; // blue // i+3 is alpha (the fourth element) } // overwrite original image context.putImageData(imageData, destX, destY); }; imageObj.src = "http://java2s.com/style/download.png"; }; </script> </head> <body> <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> </canvas> </body> </html>
To convert an RGB color into a gradation of gray, obtain the brightness of the color.
Then use the equation of brightness to get the grayscale value of a colored pixel.
We are most sensitive to green light, followed by red light, and are least sensitive to blue light:
Brightness = 0.34 * R + 0.5 * G + 0.16 * B
We've added more weight to the green value (most sensitive) followed by the red value (less sensitive) followed by the blue value (least sensitive).