views:

558

answers:

4

I'm trying to find a method for determining whether to use black or white text, given a background color (as a hex value). Has anyone dealt with this before? Is there an effective way to do this?

In my case, I would be using PHP to implement the logic (though any experience with this in other languages is welcome).

+1  A: 

A simple but not perfect solution would be to sum the individual components (RGB) and the larger this value the 'lighter the color'. So for a high value you could use black as the foreground, and for a low value, use white.

You could then improve this method, making specific cases for greyscale colors (R = G = B), which, except for very dark grey, won't display white text well.

Edit: This of course means you need to know the format of RGB storage in your hex value, standard 24bpp storage is 0x00RRGGBB for the 8 hex digits.

DeusAduro
+13  A: 

Take a look at this page: Calculating Color Contrast with PHP

Keep in mind that if black and white are your only choices you're bound to have cases where neither of them works particularly great.

ChssPly76
+1 Calculating the luminance or brightness of the color is far superior to averaging the RGB values. #FF0000 is bright red, not a dark color that the average of 85 would lead you to believe. In the HSB system (0-100% scale for B), you get B=100 for bright red. In the Lab system, you only get 54, probably more useful, since it's above the 50% point, indicating that you should use black against it, not white.
Warren Young
That's a great find!
Wilco
A: 

i would calculate the average value of rgb components and then decide whether to use black or white, e.g. white up to 0x66

knittl
+2  A: 

Here is an algorithm that can be used to calculate a luminosity contrast ratio of your text:

http://juicystudio.com/services/aertcolourcontrast.php

You could use this formula with white and black values to calculate which gives you the higher ratio, and thus more readable text.

bigmattyh