Convert image to grayscale using javascript

Ajaxblender share with us nice tutorial how to desaturate an image (convert color images to grayscale) using JavaScript. This image manipulation is relatively simple , there are two methods (one method for Internet Explorer and one method for all other browsers).

desturate images Convert image to grayscale using javascript

The technique on this image manipulation is prety simple, as you probably know, screen color consists of 3 components: red, green and blue. Each component or color has a value from 0 to 255. The value 0 indicates there is no red color and the value 255 would be the brightest possible red color. To convert a color to grayscale you just need to calculate the average for all three components. This can be done using the simple formula below:

grayscalecolor = (red + green + blue) / 3;

The formula above then implemented to canvas , first time we need to create a canvas, loaded the image into it, and then changed the color values of each pixel in the image to an average value. After that we simply replaced the SRC of our image to the image changed in the canvas.

Requirements: CANVAS tag support browser
Demo: http://www.ajaxblender.com/article-sources/jquery/convert-image-grayscale/index.html
View tutorial : http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html

Incoming search terms for the article:

Related Posts

Colorize Your Source Code With Sunlight

Mozilla Tow Truck: Real-Time Web Browser Collaboration

Create Cool Charts And Graphs Via HTML5 Using Chart.js

Lazy Line Painter

2 Comments

  1. oweynge

    12.10.2009

    this won’t give the correct/accurate luminance. the (gray) colors will be a bit off. This is because we perceive the luminance of colors differently (red and green seem “brighter” than blue)

    There are many other ways of converting the RGB values, here’s one used for analog TV:
    grayscalecolor = (0.3 * red + 0.59*green + 0.11*blue);

    great example, though :)
    oweynge´s last blog ..Dream My ComLuv Profile

    • mupet

      12.10.2009

      Hi oweynge, thanks for giving alternative solution, this information very useful, the developers maybe can do experiment with this formula

      grayscalecolor = (0.3 * red + 0.59*green + 0.11*blue);

      very nice