Jud*_*ing 29 php hex colors brightness
我希望我网站上的用户能够选择十六进制颜色,我只想显示深色的白色文本和浅色的黑色文本.你能用十六进制代码(最好是PHP)来计算亮度吗?
0sc*_*car 44
$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
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*key 19
我做了一个类似的 - 但基于每种颜色的权重(基于此线程的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
Run Code Online (Sandbox Code Playgroud)
编辑: 小优化: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
Run Code Online (Sandbox Code Playgroud)
它根本不应用sqrt,而是将所需的截止对比度提高2,这是一个便宜得多的计算
我知道这是一个非常古老的话题,但对于来自“Google 搜索”的用户来说,这个链接可能就是他们正在寻找的内容。我搜索过类似的内容,我认为将其发布在这里是个好主意:
https://github.com/mexitek/phpColors
use Mexitek\PHPColors\Color;
// Initialize my color
$myBlue = new Color("#336699");
echo $myBlue->isLight(); // false
echo $myBlue->isDark(); // true
Run Code Online (Sandbox Code Playgroud)
就是这样。
| 归档时间: |
|
| 查看次数: |
11858 次 |
| 最近记录: |