Tips To Convert Images to Grayscale

Tips To Convert Images to Grayscale

Many photo editors such as Photoshop let you turn colorful images into grayscale easily. There is even the option to tune the color depth and color tones. Unfortunately, it is less straightforward to do so on the Web due to the differences in browser capabilities.We are going to walk through some methods that we can use to turn images grayscale.we will combine these methods to achieve a grayscale image that works across different browsers.
CSS Filter

Using CSS filter property is perhaps the easiest way to turn image into grayscale. Back in the old day, Internet Explorer has a proprietary CSS property called filter to apply custom effect including Grayscale.

This code will take effect in IE6-9 and Webkit browsers (Chrome 18+, Safari 6.0+, and Opera 15+).

(Note: IE10 dropped support for the legacy IE filter nor it also support for the prefixed version, -ms-filter, for applying grayscale. This code does not work in Firefox either.)

The second alternative is by using JavaScript, which technically should work in all browsers that have JavaScript enabled, including IE6 and below.


Another way is by using an SVG Filter.

<svg xmlns=””>
<filter id=”grayscale”>
<feColorMatrix type=”matrix” values=”0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0″/>

All you need to do is create an SVG file, and put the following codes in it. Save and name the file to e.g. gray.svg.Then, using the filter property, we link the SVG file followed by the ID of the filter element in our SVG file:

You can also embed the codes directly within the CSS, like so.

This will return the same result.

Cross Browser

To have cross-browser support for the grayscale effect, we can put the abovementioned methods together, using the following code snippet. This code will apply the grayscale effect in Firefox 3.5+, Opera 15+, Safari, Chrome, and Internet Explorer.

We can utilize the above code along with the JavaScript method, and only provide CSS filter as the fallback in case JavaScript is disabled. This idea can easily be achieved with the help of Modernizr.

Modernizr will add js class in the body, if JavaScript is enabled, and it will switch the class name to no-js if it is disabled. With CSS, you can do the following.