Evaluate whether a HEX value is dark or light

喜欢而已 提交于 2019-11-30 04:05:18

Instead of adding the RGB components together like the other answerer (ricknz) said, you should actually take the average of them.

Also, since green is more visible to the human eye than blue, you should also add a weight.

So you have to multiply the Red component first times 0.299, the Green times 0.587 and the Blue times 0.114

so the luminance is given by: Luminance = (r*0.299 + g*0.587 + b*0.114)/3

edit: here is a snippet which calculates it:

 float calcLuminance(int rgb)
 {
      int r = (rgb & 0xff0000) >> 16;
      int g = (rgb & 0xff00) >> 8;
      int b = (rgb & 0xff);

      return (r*0.299f + g*0.587f + b*0.114f) / 256;
 }

p.s. the division by 256 since we the RGB ran from 0-256 (instead of 0-1)

edit: changed the calculcation as to divide by 256 and not 768 as cleverly commented

Johannes Hoff

Convert to HSL and look at the Luminance value. This will tell you how bright it is.

Here is a javascript function for doing the conversion.

The methods to do this are built into .Net now:

    var hexcolor = "#FA3CD0";
    var color = System.Drawing.ColorTranslator.FromHtml(hexcolor);
    var brightness = color.GetBrightness();
    if (brightness > .5)
    {
        // color is light
    }
    else
    {
        // color is dark
    }

A hex color code is composed of three intensity values, one for red, one for green and one for blue, with 2 hex digits for each. To determine dark vs. light, simply add the three values together. Smaller numbers would be darker than larger values.

For #010203, adding the RGB values together gives 01+02+03 = 06. That will be darker than #102030 = 60.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!