Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding out if a Hex color is dark or light

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?

like image 417
sam360 Avatar asked Dec 02 '22 15:12

sam360


2 Answers

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

like image 136
Touk Avatar answered Dec 15 '22 03:12

Touk


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.

like image 35
Jon Avatar answered Dec 15 '22 02:12

Jon