How can I detect intensity of this hex color: #000000
? I can use that method for this code. For example if background color is black, text-color must be set to #FFFFFF
(white). I'm using this snippet for generating random color:
$random_color = '#'.base_convert(rand(0, 16777215), 10, 16);
There're couple of valid approaches but the simpliest is to convert your color to grayscale and then check if result value is in upper half or lower. If in upper, then it's light color and you should use i.e. black as text color, if in lower, then it's dark, so white will work best. Something like this:
function getReadableTextColor( $backgroundColor ) {
$R = ($backgroundColor >> 16 ) & 0x000000ff;
$G = ($backgroundColor >> 8 ) & 0x000000ff;
$B = ($backgroundColor ) & 0x000000ff;
// grayscale: 0.3RED + 0.59GREEN + 0.11Blue
$K = (($R * 0.3) + ($G * 0.59) + ($B * 0.11));
// black fg color for light background, white for dark ones
return ( $K > 128 ) ? 0x000000 : 0xffffff;
}
then use like this
$bgColor = rand(0, 16777215);
$bgcolorHTML = '#' . base_convert($bgColor, 10, 16);
$fgColor = getReadableTextColor( $bgColor );
$fgColorHtml = '#' . base_convert($fgColor, 10, 16);
I think, You need to calculate the negative color for good readability. Try this function:
<?php
function NegativeColor($color)
{
$r = substr($color, 0, 2);
$g = substr($color, 2, 2);
$b = substr($color, 4, 2);
//Invert colors, (255 - colVal)
$r = 0xff-hexdec($r);
$g = 0xff-hexdec($g);
$b = 0xff-hexdec($b);
return str_pad(dechex($r),2,0,STR_PAD_LEFT)
.str_pad(dechex($g),2,0,STR_PAD_LEFT)
.str_pad(dechex($b),2,0,STR_PAD_LEFT);
}
var_dump(NegativeColor('000000'));
//output : string(6) "ffffff"
?>