Php 生成随机颜色

Php 生成随机颜色,php,Php,我正在使用此代码生成随机颜色(工作正常): 我只是想知道是否有一种方法/组合只产生明亮的颜色 谢谢我使用此代码检测背景颜色是浅还是暗,然后选择正确的字体颜色,因此字体颜色在随机生成或用户输入的背景颜色上仍然可读/可见: //$hex: #AB12CD function ColorLuminanceHex($hex=0) { $hex = str_replace('#', '', $hex); $luminance = 0.3 * hexdec(substr($hex,0,2)) + 0.

我正在使用此代码生成随机颜色(工作正常):

我只是想知道是否有一种方法/组合只产生明亮的颜色


谢谢

我使用此代码检测背景颜色是浅还是暗,然后选择正确的字体颜色,因此字体颜色在随机生成或用户输入的背景颜色上仍然可读/可见:

//$hex: #AB12CD
function ColorLuminanceHex($hex=0) {
  $hex = str_replace('#', '', $hex);
  $luminance = 0.3 * hexdec(substr($hex,0,2)) + 0.59 * hexdec(substr($hex,2,2)) + 0.11 * hexdec(substr($hex,4,2));
  return $luminance;
}


$background_color = '#AB12CD';
$luminance = ColorLuminanceHex($background_color);
if($luminance < 128) {
  $color = '#FFFFFF';
}
else {
  $color = '#000000';
}
/$hex:#AB12CD
函数ColorLuminanceHex($hex=0){
$hex=str#u替换('#',''$hex);
$luminance=0.3*hexdec(substr($hex,0,2))+0.59*hexdec(substr($hex,2,2))+0.11*hexdec(substr($hex,4,2));
返回$luminance;
}
$background_color='#AB12CD';
$luminance=ColorLuminanceHex($background\u color);
如果($亮度<128){
$color='#FFFFFF';
}
否则{
$color='000000';
}

您的原始代码没有如您所期望的那样工作-如果生成一个较低的数字,您可能会得到
#1fff
(1是较低的红色值)-这是无效的。使用此选项更稳定:

echo "rgb(".$r.",".$g.",".$b.")";
由于
rgb(123,45,67)
是完全有效的颜色规格

类似地,您可以为hsl生成随机数:

echo "hsl(".rand(0,359).",100%,50%)";
这将产生任何色调的完全饱和、正常明度颜色。但是,请注意,只有最近的浏览器才支持HSL,因此如果浏览器支持是一个问题,您最好与RGB联合使用。

使用上面的chakroun yesser,我创建了此函数:

function getRandomColor() {
    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    return $color;
}
function generateRandomColor($count=1){
    if($count > 1){
        $color = array();
        for($i=0; $count > $i; $i++)
            $color[count($color)] = generateRandomColor();
    }else{
        $rand = array_merge(range(0, 9), range('a', 'f'));
        $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    }
    return $color;
}

您可以在HSL/HSV中生成颜色,然后转换为RGB。
function generateRandomColor($count=1){
    if($count > 1){
        $color = array();
        for($i=0; $count > $i; $i++)
            $color[count($color)] = generateRandomColor();
    }else{
        $rand = array_merge(range(0, 9), range('a', 'f'));
        $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    }
    return $color;
}