views:

137

answers:

3

I am looking to find a why to calculate a suitable background colour and a colour for the text that would go over the top, obviously I need to take into account readability and accessibility.

I would need to pick the two colours from the array, the colours are stored in their hex representations.

#CC9966
#996633
#FFCC99
#CCCC99
#000000
#333333
#666633
#663333
#CC9933
#FFCCCC

I can use a PHP library like GD / imageMagick?

Any suggestions (Please note I am using PHP)

A: 

Break each color into its RGB components, add 0x80 (or some other similar value, perhaps 0x66) to each, mask by 0xff, and find the closest value in the table.

Ignacio Vazquez-Abrams
Do you mean something like $newRed = (($rgb['red'] + 0x80) * 0xFF); Where $rgb['red'] is something like 163
Lizard
Ignacio Vazquez-Abrams
+1  A: 

Choosing random colours is usually not a good idea for readability and accessibility, so I'd suggest that you rethink your design. Or at least limit the text to only black or white.

If that is not an option then I'd suggest calculating a "distance" between two colours that would be approximately equal to the visual difference between the colours, and thus also somewhat related to the readability.

I would use distance = abs(2*(r1-r2) + 3*(g1-g2) + (b1-b2)), and then filter out any combination that does not have a sufficiently high distance. This should ensure that you end up with either a dark colour on a bright background, or a bright colour on a dark background, which is pretty much a prerequisite for good readability, and ensures that colour blind people will also see two clearly distinct shades. The colour components are weighted differently since they have a different impact on the total perceived brightness.

eBusiness
+1  A: 

First of all I think you should take a look at this excellent blog post at Particletree.

That being said, I would use their smarty_modifier_contrast() function and modify it a little bit to address your specific needs, something like:

function color_contrast($bgcolor, $color1, $color2, $color3, ...)
{
    return (hexdec($bgcolor) > 0xffffff / 2) ? min(array_slice(func_get_args(), 1)) : max(array_slice(func_get_args(), 1));
}

So you would just need to use any random color for the background (don't forget to drop the #!) and then pass all the other colors to the array, in this case I've used a variable number of arguments but you can change it so that it accepts a single array of colors - it will then automatically pick the darkest or the lightest color depending on the $bgcolor and provide a good enough contrast for readability:

function color_contrast($bgcolor, $colors = array())
{
    return (hexdec($bgcolor) > 0xffffff / 2) ? min($colors) : max($colors);
}

To pick the $bgcolor, you can do it randomly like I said before of use a second function to help you with this task like saturation or luminance, that really depends what you're looking for.

Alix Axel