There are plenty of different ways to convert images to black and white, but using Css is the most appropriate approach because layout, colors, textures, shadows.. are all the area of Css.
In addition to that, the Css grayscale function can be combined with animations, transitions, hover.. to achieve complex effects like fading, rollover, … and Css is getting better and better at this.
HTML markup :
<img src="my_picture.jpg" class="grayscale" />
The image can be declared in the html markup (as above) or in a Css class.
CSS markup :
To make our images into black and white in a cross browser way we will use three filter values : the standard Css filter for Webkit browsers, Svg filter for Firefox and Microsoft filter property for IE 6+ :
/* for Webkit browsere, Chrome 19+, Safari 6+ ... */
/* this is for Firefox 3.5+, Firefox mobile */
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'gs\'><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\'/></filter></svg>#gs");
/* for IE6+ */
Here's the result :
The first image is the original, the second is the grayscaled version and the third picture will be recolored to black and white on mouse hover.
The standard Css3 filter property is now only supported by Webkit browsers via their vendor prefix, but we can add the following lines to future-proof our code, when other browsers will implement this new feature either via their vendor prefixes or directly :
This Css grayscale code doesn't work on Opera for now (april 2013), but I think Opera will implement Css3 filters and will soon support this.
Chtiwi Malek on Google+
About the author :
Malek Chtiwi is the man behind Codicode.com
34 years old full stack developer.
Loves technology; but also likes design, photography and composing music.