使用PHP生成高对比度随机颜色

时间:2013-01-23 19:51:51

标签: php random colors

我需要为系统中的所有用户生成随机颜色。诀窍是2个用户不能有非常相似的颜色,他们需要区分。我有代码在给定原始混合颜色的情况下生成随机颜色,但无法找到一种仅使用PHP生成具有高对比度的随机颜色的方法

public static function generateRandomColor($rgb)
{
    $red = rand(1, 256);
    $green = rand(1, 256);
    $blue = rand(1, 256);

    if (! empty($rgb))
    {
        $red = ($red + $rgb['red']) / 2;
        $green = ($green + $rgb['green']) / 2;
        $blue = ($blue + $rgb['blue']) / 2;
    }

    $color = "rgb({$red}, {$green}, {$blue})";

    return $color;
}

然后我有一个循环:

$colorsArr = array();
$mixed = array('red' => 255, 'green' => 255, 'blue' => 255);
for($i = 0; $i < count($users); $i++)
{
    $color = generateRandomColor($mixed);

    $colorsArr .= '<div style="width:25px; height: 25px; background-color: ' . $color . '"></div>';
}

现在这会产生颜色,但有些颜色看起来像是彼此。目标是为每个用户提供独特的颜色。 任何帮助表示感谢。

注意:我不想硬编码500个用户的颜色

1 个答案:

答案 0 :(得分:3)

我感到无聊,这里有一些你可以随意使用的代码:

<?php
define( COL_MIN_AVG, 64 );
define( COL_MAX_AVG, 192 );
define( COL_STEP, 16 );

// (192 - 64) / 16 = 8
// 8 ^ 3 = 512 colors

function usercolor( $username ) {
        $range = COL_MAX_AVG - COL_MIN_AVG;
        $factor = $range / 256;
        $offset = COL_MIN_AVG;

        $base_hash = substr(md5($username), 0, 6);
        $b_R = hexdec(substr($base_hash,0,2));
        $b_G = hexdec(substr($base_hash,2,2));
        $b_B = hexdec(substr($base_hash,4,2));

        $f_R = floor((floor($b_R * $factor) + $offset) / COL_STEP) * COL_STEP;
        $f_G = floor((floor($b_G * $factor) + $offset) / COL_STEP) * COL_STEP;
        $f_B = floor((floor($b_B * $factor) + $offset) / COL_STEP) * COL_STEP;

        return sprintf('#%02x%02x%02x', $f_R, $f_G, $f_B);
}

for( $i=0; $i<30; $i++ ) {
        printf('<div style="height: 100px; width: 100px; background-color: %s">&nbsp;</div>'."\n", usercolor(rand()));
}

许多颜色看起来非常相似,但它们彼此相邻的可能性很小。

相关问题