How to find the negative of a color in hexadecimal?

Asked

Viewed 1,527 times

5

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

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

`#FFFFFF => #000000`

Or

 0xFFFFFF => 0x000000

3 answers

9


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

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

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

To invert a color, invert 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 of Angular/Java code that performs this operation follows below:

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>
    <div ng-controller="SampleController">
      
      Cor: #<input type='text' ng-model='sourceValue'>
      <br />
      
      Inversa: {{ inverseColor() }}
    </div>
  </body>
</html>

3

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

  • Actually, that’s what a friend told me: you have to use the RGB value to do this :|

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.