I am trying to create a small script which generates two colors which, if one used as background and one as font-color, will be readable according to the following guidelines:
http://www.hgrebdes.com/colour/spectrum/colourvisibility.html
Web Accessibility Guidelines from the W3C (and inadequate)
Color visibility can be determined according to the following algorithm:
(This is a suggested algorithm that is still open to change.)
Two colors provide good color visibility if the brightness difference and the color difference between the two colors are greater than a set range.
Color brightness is determined by the following formula: ((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000 Note: This algorithm is taken from a formula for converting RGB values to YIQ values. This brightness value gives a perceived brightness for a color.
Color difference is determined by the following formula: (maximum (Red value 1, Red value 2) - minimum (Red value 1, Red value 2)) + (maximum (Green value 1, Green value 2) - minimum (Green value 1, Green value 2)) + (maximum (Blue value 1, Blue value 2) - minimum (Blue value 1, Blue value 2))
The range for color brightness difference is 125. The range for color difference is 500.
My code is:
do {
$bg[0] = rand(0, 255);
$bg[1] = rand(0, 255);
$bg[2] = rand(0, 255);
$bg[3] = ($bg[0] + $bg[1] + $bg[2])/1000;
$txt[0] = rand(0, 255);
$txt[1] = rand(0, 255);
$txt[2] = rand(0, 255);
$txt[3] = ($txt[0] + $txt[1] + $txt[2])/1000;
//Brightness Difference = Brightness of color 1 - Brightness of color 2
$brightnessDifference = abs($bg[3] - $txt[3]);
//Color difference = Maximum (Red1, Red2) - Minimum (Red1, Red2) etc for Blue and Green
$colorDifference = max($bg[0], $txt[0]) - min($bg[0], $txt[0]) + max($bg[1], $txt[1]) - min($bg[1], $txt[1]) + max($bg[2], $txt[2]) - min($bg[2], $txt[2]);
} while($brightnessDifference < 125 || $colorDifference < 500)
But the execution time exceeds the one allowed by PHP... Suggestions on how I could optimize it? :)