十六进制代码亮度 PHP?

2022-08-30 14:29:16

我希望我的网站上的用户能够选择十六进制颜色,我只想显示深色的白色文本和浅色的黑色文本。你能从十六进制代码(最好是PHP)中计算出亮度吗?


答案 1
$hex = "78ff2f"; //Bg color in hex, without any prefixing #!

//break up the color in its RGB components
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));

//do simple weighted avarage
//
//(This might be overly simplistic as different colors are perceived
// differently. That is a green of 128 might be brighter than a red of 128.
// But as long as it's just about picking a white or black text color...)
if($r + $g + $b > 382){
    //bright color, use dark font
}else{
    //dark color, use bright font
}

答案 2

我做了一个类似的 - 但基于每种颜色的权重(基于此线程的C#版本)

function readableColour($bg){
    $r = hexdec(substr($bg,0,2));
    $g = hexdec(substr($bg,2,2));
    $b = hexdec(substr($bg,4,2));

    $contrast = sqrt(
        $r * $r * .241 +
        $g * $g * .691 +
        $b * $b * .068
    );

    if($contrast > 130){
        return '000000';
    }else{
        return 'FFFFFF';
    }
}

echo readableColour('000000'); // Output - FFFFFF

编辑:小优化:Sqrt被称为昂贵的数学运算,在大多数情况下可能是可以忽略的,但无论如何,可以通过做这样的事情来避免。

function readableColour($bg){
    $r = hexdec(substr($bg,0,2));
    $g = hexdec(substr($bg,2,2));
    $b = hexdec(substr($bg,4,2));

    $squared_contrast = (
        $r * $r * .299 +
        $g * $g * .587 +
        $b * $b * .114
    );

    if($squared_contrast > pow(130, 2)){
        return '000000';
    }else{
        return 'FFFFFF';
    }
}

echo readableColour('000000'); // Output - FFFFFF

它根本不应用 sqrt,而是将所需的截止对比度提高 2,这是一个更便宜的计算


推荐