6

Using C# I'd like to find out if a Hex color (web format, e.g: #FF2233) is dark or light based on which I can decide what the fore color (font color) should be.

The color is selected by application's users as background of certain elements. The program then needs to figure out if the user's background color is dark then choose white as the font color (for best readability and contrast) otherwise black is chosen.

So far I have been trying to count the number of occurrences of the "F","E","C","D","B" and "A". If there are at least 4 occurrences I consider the color bright. It works for about 70% of times.

Is there a better solution for this?

sam360
  • 1,121
  • 3
  • 18
  • 37

2 Answers2

17

What if you convert your [Hex color to rgb][1] format then you make the summ of red green and blue if it's over ((255*3)/2) it's a dark color, else it's light color.

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FF2233");
if (col.R * 0.2126 + col.G * 0.7152 + col.B * 0.0722 < 255 / 2)
{
 // dark color
}
else
{
 // light color
}

Edit: Updated with Luminance, thanks to @Jon idea [1]: How do I get the color from a hexadecimal color code using .NET?

Edit: fixed condition, thanks to @sam360

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
Touk
  • 459
  • 2
  • 14
  • Is it possible to favor towards dark color by adjusting the number? For example #3f994a is being recognized as bright color. – sam360 Oct 30 '14 at 14:05
  • Yeah, you will have to change "255 / 2", if you put "255 / 3" you will have more colors recognized as bright than dark, and if you put something like "(255 / 3) * 2" you will have more dark colors than bright colors – Touk Oct 31 '14 at 20:45
  • 2
    I think the condition is reversed, if the number is bigger than 127.5 is bright and less can be considered as dark. – sam360 Nov 23 '14 at 01:38
  • Late, but this is a helpful answer! – WhoMightThisOneBe Dec 17 '18 at 08:45
7

It's pretty straightforward to compute the luminance of the color from the RGB components. While this will not give the most accurate result on the planet if judged from a human's perspective, it's going to be massively better than other naive attempts.

Given the values of the color components R, G, B, the luminance Y is

Y = 0.2126 R + 0.7152 G + 0.0722 B

You would then pick an arbitrary threshold for Y that separates "dark" from "light" colors.

Jon
  • 428,835
  • 81
  • 738
  • 806