How To Convert Image to Black and White


Convert Images to Black and White using jQuery

Convert Images to Black and White using jQuery is no longer a manual event. As client side technologies becoming more powerful, conversion processes can be automated and be done in real-time. Read on to learn different ways of converting images to black and white using CSS3, HTML5 with jQuery and various other jQuery plugins.

There are jQuery plugins available which can do this job, but first we look at how to do it with simple CSS. Then we will move on to using jQuery code, and finally jQuery plugins. It is best to avoid jQuery plugins until they are absolutely necessary.

CSS

CSS3 supports various filters and filter properties providing graphical effects like blurring, sharpening, or color shifting an element. Filters are commonly used to adjust the rendering of images, backgrounds, and borders. So we can apply the grayscale filter to convert images to black and white. Like this:

img {

-webkit- filter: grayscale(100%); /* Safari 6.0 – 9.0 */

filter: grayscale(100%);

}

This filter also takes a parameter which defines the proportion of the conversion. The value 100% means “completely grayscale”. And the range is from 0% to 100%. If not specified, then 100% will be used.

The above CSS3 filter gets applied to all images upon loading of the page. If you wish to apply the filter on user action, a click for example, then define a CSS and then using jQuery addClass() apply the class. Like this:

.blackandwhite {

-webkit – filter: grayscale(100 % ); /* Safari 6.0 – 9.0 */

filter: grayscale(100 % );

}

$(‘#btnConvert’).click(function() {

$(‘img’).addClass(‘blackandwhite’);

});

jQuery

If you don’t wish to use CSS then HTML5 Canvas can be used to convert images to black and white. Canvas is an empty element on which you can write and sketch using jQuery/JavaScript.

<input type=”button” id=”btnConvert” Value=”Convert” />

<canvas id=”canBoard”/>

<img id=”imgTest” style=”display:none;” height=”200″ width=”300″ /><br/>

 

Leave a Reply

Your email address will not be published. Required fields are marked *