How to find the negative of a color in hexadecimal?

4

I would like to know what calculation I can use in language like javascript , php or python to find the negative of a cor hexadecimal.

Example: If white negative is black, then I assume:

'#FFFFFF => #000000'

Or

 0xFFFFFF => 0x000000
    
asked by anonymous 11.12.2015 / 14:34

3 answers

7

The inverse color can be calculated via exclusive OR (XOR) versus the maximum value (#FFFFFF).

The hexadecimal color format is already a hint of how to do this: each of the double octets in #RRGGBB represents a primary color whose intensity can range from # 00 to #FF (255 in decimal).

In other words, each primary color is represented by 8 bits.

To invert a color, reverse the bits:

Cor     Valor HEX valor BIN                     BIN invertido                 HEX invertido
Preto   #000000   B00000000 00000000 00000000   B11111111 11111111 11111111   #FFFFFF    
Branco  #FFFFFF   B11111111 11111111 11111111   B00000000 00000000 00000000   #000000
Azul    #0000FF   B00000000 00000000 11111111   B11111111 11111111 00000000   #FFFF00

An example code in Angular / javaScript that performs this operation follows:

function SampleController($scope) {
  $scope.sourceValue = 0;
  $scope.inverseColor = function(){
    var srcVal = $scope.sourceValue;
    var valNumerico = parseInt(srcVal, 16);
    var mascara = parseInt('FFFFFF', 16);
    var dest = valNumerico ^ mascara; //Operação XOR
    return dest.toString(16);
  };  
}
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script></head><body><divng-controller="SampleController">
      
      Cor: #<input type='text' ng-model='sourceValue'>
      <br />
      
      Inversa: {{ inverseColor() }}
    </div>
  </body>
</html>
    
11.12.2015 / 15:02
2

I found an example in PHP :

function color_inverse($color){
    $color = str_replace('#', '', $color);
    if (strlen($color) != 6){ return '000000'; }
    $rgb = '';
    for ($x=0;$x<3;$x++){
        $c = 255 - hexdec(substr($color,(2*$x),2));
        $c = ($c < 0) ? 0 : dechex($c);
        $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
    }
    return '#'.$rgb;
}

Testing:

// preto -> branco
print color_inverse('#000000'); 
// --> retorna #ffffff

Credits: Link

    
11.12.2015 / 14:44
1

If it's for display only you can solve this in CSS

-webkit-filter: invert(100%);
filter: invert(100%);

Via Javascript has the solution in this other question. link

    
11.12.2015 / 14:42