Invert colors of an image in CSS or JavaScript

JavascriptCssColors

Javascript Problem Overview


How do I invert colors of an image (jpg/png..) in either css if possible or javascript?

Previous related questions don't give enough detail.

Javascript Solutions


Solution 1 - Javascript

CSS3 has a new filter attribute which will only work in webkit browsers supported in webkit browsers and in Firefox. It does not have support in IE or Opera mini:

img {
   -webkit-filter: invert(1);
   filter: invert(1);
   }

<img src="http://i.imgur.com/1H91A5Y.png">

Solution 2 - Javascript

Can be done in major new broswers using the code below

.img {
	-webkit-filter:invert(100%);
     filter:progid:DXImageTransform.Microsoft.BasicImage(invert='1');
}

However, if you want it to work across all browsers you need to use Javascript. Something like this gist will do the job.

Solution 3 - Javascript

You can apply the style via javascript. This is the Js code below that applies the filter to the image with the ID theImage.

function invert(){
document.getElementById("theImage").style.filter="invert(100%)";
}

And this is the

<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png"></img>

Now all you need to do is call invert() We do this when the image is clicked.

function invert(){
document.getElementById("theImage").style.filter="invert(100%)";
}

Click image to invert

<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png" onClick="invert()" ></img>

We use this on our website

Solution 4 - Javascript

For inversion from 0 to 1 and back you can use this library InvertImages, which provides support for IE 10. I also tested with IE 11 and it should work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlaggingreflexView Question on Stackoverflow
Solution 1 - Javascripttoxicate20View Answer on Stackoverflow
Solution 2 - JavascriptKareemView Answer on Stackoverflow
Solution 3 - JavascriptSabba KeynejadView Answer on Stackoverflow
Solution 4 - JavascriptomalyutinView Answer on Stackoverflow