获取十六进制背景颜色的反色值 - PHP

3
我在页面上有一个日历,其中的事件背景颜色是预设的颜色(深蓝或暗红色)。背景颜色已经成功应用。(如图片所示)

CALENDAR IMAGE WITH COLORDED ROWS

现在我要应用前景色|文本颜色,使其易于阅读。(可以是与我现有的相反的"黑色"=>"白色"或"深棕色"=>"白色")。
以下是我目前所做的。
public static function GenerateInverseColor($color){


        $color       = trim($color);
        $prependHash = FALSE;

        if(strpos($color,'#')!==FALSE) {
            $prependHash = TRUE;
            $color       = str_replace('#',NULL,$color);
        }

        switch($len=strlen($color)) {
            case 3:
                $color=preg_replace("/(.)(.)(.)/","\\1\\1\\2\\2\\3\\3",$color);
                break;
            case 6:
                break;
            default:
                trigger_error("Invalid hex length ($len). Must be a minimum length of (3) or maxium of (6) characters", E_USER_ERROR);
        }

        if(!preg_match('/^[a-f0-9]{6}$/i',$color)) {
            $color = htmlentities($color);
            trigger_error( "Invalid hex string #$color", E_USER_ERROR );
        }

        $r = dechex(255-hexdec(substr($color,0,2)));
        $r = (strlen($r)>1)?$r:'0'.$r;
        $g = dechex(255-hexdec(substr($color,2,2)));
        $g = (strlen($g)>1)?$g:'0'.$g;
        $b = dechex(255-hexdec(substr($color,4,2)));
        $b = (strlen($b)>1)?$b:'0'.$b;

        return ($prependHash?'#':NULL).$r.$g.$b;
}

另外,我已经尝试过

// provide balck|white color for any color
public static function GenerateInverseColor($hexcolor){

        $hexcolor       = trim($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';

}

而且

public static function GenerateInverseColor($hexcolor){
 if (strlen($color) != 6){ return '000000'; }
    $rgb = '';
    for ($x=0;$x<3;$x++){
        $c = 255 - hexdec(substr($color,(2*$x),2));
        $c = ($c < 0) ? 0 : dechex($c);
        $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
    }
    return '#'.$rgb;
}

这些方法都无法提供所需的输出。

我尝试了几乎所有我能找到的答案,但是没有一个有帮助。图像中的颜色组合也基于SO上的一些答案,但无法满足我的要求。


你确定你的问题不是 https://dev59.com/H5jga4cB1Zd3GeqPJ2t1 的重复吗? - Andrei Lupuleasa
是的,我也检查过那个答案,但它并没有帮助。 - ahmednawazbutt
它给出的颜色几乎与背景相同(几乎,不完全相同) - ahmednawazbutt
1个回答

1
我曾经在PHP中使用ColorJizz库来操作颜色。我记得它应该有用于计算文本/背景的方法。
请注意,仅通过数学方式处理随机颜色并不能保证良好的UI效果。颜色感知比其组成更为复杂。更不用说你可能会得到对比度很高但美观度很差的颜色了。

抱歉,但我不能自由地使用库来完成这个任务。 - ahmednawazbutt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接