Given a background color, black or white text?

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).


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.


I think the best way is the Luminosity Contrast algorithm :

ADVISE: The next functions works well most of the time, But sometimes there are colors in which it does not work properly.

public function getContrastColor($hexColor) {

        //////////// hexColor RGB
        $R1 = hexdec(substr($hexColor, 0, 2));
        $G1 = hexdec(substr($hexColor, 2, 2));
        $B1 = hexdec(substr($hexColor, 4, 2));

        //////////// Black RGB
        $blackColor = "#000000";
        $R2BlackColor = hexdec(substr($blackColor, 0, 2));
        $G2BlackColor = hexdec(substr($blackColor, 2, 2));
        $B2BlackColor = hexdec(substr($blackColor, 4, 2));

         //////////// Calc contrast ratio
         $L1 = 0.2126 * pow($R1 / 255, 2.2) +
               0.7152 * pow($G1 / 255, 2.2) +
               0.0722 * pow($B1 / 255, 2.2);

        $L2 = 0.2126 * pow($R2BlackColor / 255, 2.2) +
              0.7152 * pow($G2BlackColor / 255, 2.2) +
              0.0722 * pow($B2BlackColor / 255, 2.2);

        $contrastRatio = 0;
        if ($L1 > $L2) {
            $contrastRatio = (int)(($L1 + 0.05) / ($L2 + 0.05));
        } else {
            $contrastRatio = (int)(($L2 + 0.05) / ($L1 + 0.05));
        }

        //////////// If contrast is more than 5, return black color
        if ($contrastRatio > 5) {
            return 'black';
        } else { //////////// if not, return white color.
            return 'white';
        }
}

Some results:

在这里输入图像描述

NOTE: The font color is determined by the previous function. The number in brackets is the contrast ratio.



Another simpliest and less precise way called YIQ (because it converts the RGB color space into YIQ):

public function getContrastColor($hexcolor) {               
    $r = hexdec(substr($hexcolor, 0, 2));
    $g = hexdec(substr($hexcolor, 2, 2));
    $b = hexdec(substr($hexcolor, 4, 2));
    $yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000;
    return ($yiq >= 128) ? 'black' : 'white';
}                   

  function getTextColour($hex){
    list($red, $green, $blue) = sscanf($hex, "#%02x%02x%02x");
    $luma = ($red + $green + $blue)/3;

    if ($luma < 128){
      $textcolour = "white";
    }else{
      $textcolour = "black";
    }
    return $textcolour;
  }
链接地址: http://www.djcxy.com/p/88934.html

上一篇: 如何在CSS中使div背景颜色透明

下一篇: 给定背景颜色,黑色或白色文本?