Finding the right foreground color for a random background color
7. Januar 2011
This is basically a reminder for myself, but perhaps other people might find that interesting as well: I’m currently working on the creation of a legend, that shows colors with a short token on them. These colors are user defined, so I don’t know at configuration time, what they are and I don’t want the user to set the foreground color.
So I need the right foreground color (white or black) for the background color. I googled a bit for this. You need the human perceived luminance of the background color to determine, if it’s light or dark and set the foreground color to the opposite of this.
I found, that the common formula to determine the perceived luminance is this:
R * 0.299 + G * 0.587 + B * 0.114
If you use RGB-values with a maximum value of 255 you get a luminance value with a maximum value of 255, telling you it’s a very light color.
I used Stoyan Stefanov’s rgbcolor-library for javascript (found here: [[http://www.phpied.com/rgb-color-parser-in-javascript/]]) to properly work with this in javascript:
backgroundColor = new RGBColor(userBackground);
foregroundColor = new RGBColor('black');
if (backgroundColor.ok) {
// Calculate foreground color
if (0.299 * backgroundColor.r +
0.587 * backgroundColor.g +
0.114 * backgroundColor.b <= 128) {
// Background is dark, so foreground should be light
foregroundColor = new RGBColor('white');
}
}