Version: N/A

Type: Function

Category: Graphics

Description: The basic problem that I faced was to determine if I needed to print white or black text over a color background. Since I allowed for the background color to change in my project, I need a way for PHP to determine the color tone. I did some research and the following script is that outcome. Since reds are lighter than either blue are green, I weigh them heavier towards white. This function assigns a tone value in the range of 0 for black to 6 for white. The function then returns the HTML color code for white (FFFFFF) is the background color is dark and black (000000) for all other colors. Now I can sfaely print text on any background, even if I do not know what the actual color is.

```function color_shade(\$colorvalue)
{
//  This function accepts a string value (\$colorvalue) that is 6 characters long.
//The format of this string follows the web guideline of RRGGBB, where RR is
//a hexidecimal value from 0 to 255(FF) that represents the amount of red in
//a color. BB is the same accept for the amount of Blue and GG is the same for
//Green. There are numerous charts in print and on the Internet that can help
//you to locate a RRGGBB. As an example 808080 is medium gray.
//
//  The RRGGBB string is broken into 6 parts. Each part is multiplied by a
//lightness factor. The Red values are lighter than either Blue or Green.
//The values are totaled in a range from 0 to 6 where 0 is the darkest
//and 6 is the lightest.
//
//  Finally the function returns a value of either 000000 or FFFFFF. This
//can be used to print text over a color background. I use this to print
//white (FFFFFF) text over dark backgrounds and black (000000) text over
//medim and light backgrounds.

\$colorparts = preg_split('//', \$colorvalue, -1, PREG_SPLIT_NO_EMPTY);
\$tone = array(0.136,0.008,0.038,0.002,0.201,0.013);
\$TotalColorValue = 0;
for (\$l=0;\$l<=5;\$l++)
{
\$TotalColorValue = (hexdec(\$colorparts[\$l]) * \$tone[\$l]) + \$TotalColorValue;
}
\$TotalColorValue = floor(\$TotalColorValue);
\$result = "";

// Values 0 and 1 are dark
if (\$TotalColorValue < 2)
{ \$result = "FFFFFF";  // Set Text to White
return \$result;
}
// Values 2 and 3 are medium
if ( (\$TotalColorValue > 1) and (\$TotalColorValue < 4) )
{ \$result = "000000";  // Set text to Black
return \$result;
}
// Values 4 and 5 are light
if (\$TotalColorValue > 3 )
{ \$result = "000000";  // Set Text to Black
return \$result;
}
return \$result;
}

```