Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex Code Brightness PHP?

I want users on my website to be able to pick a hex colour, and I just want to display white text for dark colours and black text for light colours. Can you work out the brightness from a hex code (preferably PHP)?

like image 923
Juddling Avatar asked Jun 10 '10 14:06

Juddling


2 Answers

$hex = "78ff2f"; //Bg color in hex, without any prefixing #!  //break up the color in its RGB components $r = hexdec(substr($hex,0,2)); $g = hexdec(substr($hex,2,2)); $b = hexdec(substr($hex,4,2));  //do simple weighted avarage // //(This might be overly simplistic as different colors are perceived // differently. That is a green of 128 might be brighter than a red of 128. // But as long as it's just about picking a white or black text color...) if($r + $g + $b > 382){     //bright color, use dark font }else{     //dark color, use bright font } 
like image 54
0scar Avatar answered Sep 21 '22 16:09

0scar


I made one similar - but based on weightings of each colour (based on the C# version of this thread)

function readableColour($bg){     $r = hexdec(substr($bg,0,2));     $g = hexdec(substr($bg,2,2));     $b = hexdec(substr($bg,4,2));      $contrast = sqrt(         $r * $r * .241 +         $g * $g * .691 +         $b * $b * .068     );      if($contrast > 130){         return '000000';     }else{         return 'FFFFFF';     } }  echo readableColour('000000'); // Output - FFFFFF 

EDIT: Small optimisation: Sqrt is known as an expensive math operation, which is probably neglectable in most scenarios, but anyway, it could be avoided by doing something like this.

function readableColour($bg){     $r = hexdec(substr($bg,0,2));     $g = hexdec(substr($bg,2,2));     $b = hexdec(substr($bg,4,2));      $squared_contrast = (         $r * $r * .299 +         $g * $g * .587 +         $b * $b * .114     );      if($squared_contrast > pow(130, 2)){         return '000000';     }else{         return 'FFFFFF';     } }  echo readableColour('000000'); // Output - FFFFFF 

It simply doesn't apply the sqrt, instead it powers the desired cut off contrast by two, which is a much cheaper calculation

like image 27
Mikey Avatar answered Sep 20 '22 16:09

Mikey