Reputation: 833
I have a calendar in my page with given colors as event background color (dark blue or maroon color). the background color is applied just fine. (As can be seen in picture)
Now I to apply foreground | text color that can be read easily. (can be exact inverse of what I have "black"=>"white" or "dark brown"=>"white").
Here is what I have done so far
public static function GenerateInverseColor($color){
$color = trim($color);
$prependHash = FALSE;
if(strpos($color,'#')!==FALSE) {
$prependHash = TRUE;
$color = str_replace('#',NULL,$color);
}
switch($len=strlen($color)) {
case 3:
$color=preg_replace("/(.)(.)(.)/","\\1\\1\\2\\2\\3\\3",$color);
break;
case 6:
break;
default:
trigger_error("Invalid hex length ($len). Must be a minimum length of (3) or maxium of (6) characters", E_USER_ERROR);
}
if(!preg_match('/^[a-f0-9]{6}$/i',$color)) {
$color = htmlentities($color);
trigger_error( "Invalid hex string #$color", E_USER_ERROR );
}
$r = dechex(255-hexdec(substr($color,0,2)));
$r = (strlen($r)>1)?$r:'0'.$r;
$g = dechex(255-hexdec(substr($color,2,2)));
$g = (strlen($g)>1)?$g:'0'.$g;
$b = dechex(255-hexdec(substr($color,4,2)));
$b = (strlen($b)>1)?$b:'0'.$b;
return ($prependHash?'#':NULL).$r.$g.$b;
}
Also, I have tried
// provide balck|white color for any color
public static function GenerateInverseColor($hexcolor){
$hexcolor = trim($hexcolor);
$r = hexdec(substr($hexcolor,0,2));
$g = hexdec(substr($hexcolor,2,2));
$b = hexdec(substr($hexcolor,4,2));
$yiq = (($r*299)+($g*587)+($b*114))/1000;
return ($yiq >= 128) ? 'black' : 'white';
}
And Also
public static function GenerateInverseColor($hexcolor){
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;
}
none of these methods help provide the desired output.
I have tried almost every answer I could find but none are helping. The color combo in image is also based on some answer on SO but could not fulfil my requirement
Upvotes: 3
Views: 409
Reputation: 2395
I had used ColorJizz library in the past for manipulating colors in PHP. It should have methods for calculating text/background stuff, I remember using it for such task.
Note that you are not at all guaranteed good UI results from working with random colors purely mathematically. Color perception is more complicated than just its composition. Not to mention that you can end up with colors that do contrast, but look like garbage aesthetically.
Upvotes: 1