PHP int为唯一的rgb颜色

时间:2012-06-12 08:31:45

标签: php colors int rgb

我有数字1000到9999.我想有一个函数,在每个数字的rgb中获得一个独特的颜色。每次启动方法时,每个数字的颜色必须相同。添加数字时,颜色也需要非常不同。因此,数字1可以是深红色,2浅绿色等等。

希望有人知道怎么做! :)

这是我到目前为止所得到的,但颜色几乎相同,这不是我想要的!

for ($i = 1000; $i < 2099; $i++) {
  $rgb = getRGB(dechex($i));
  echo '<div style="width: 800px; height: 30px; margin-bottom: 10px; background-color: ' . rgb2html($rgb['red'], $rgb['green'], $rgb['blue']) . ';"></div>';
}

function getRGB($psHexColorString) {
  $aColors = array();
  if ($psHexColorString{0} == '#') {
    $psHexColorString = substr($psHexColorString, 1);
  }
  $aColors['red'] = @hexdec($psHexColorString{0} . $psHexColorString{1});
  $aColors['green'] = @hexdec($psHexColorString{2} . $psHexColorString{3});
  $aColors['blue'] = @hexdec($psHexColorString{4} . $psHexColorString{5});
  return $aColors;
}

function rgb2html($r, $g = -1, $b = -1) {
  if (is_array($r) && sizeof($r) == 3)
    list($r, $g, $b) = $r;

  $r = intval($r);
  $g = intval($g);
  $b = intval($b);

  $r = dechex($r < 0 ? 0 : ($r > 255 ? 255 : $r));
  $g = dechex($g < 0 ? 0 : ($g > 255 ? 255 : $g));
  $b = dechex($b < 0 ? 0 : ($b > 255 ? 255 : $b));

  $color = (strlen($r) < 2 ? '0' : '') . $r;
  $color .= (strlen($g) < 2 ? '0' : '') . $g;
  $color .= (strlen($b) < 2 ? '0' : '') . $b;
  return '#' . $color;
}

2 个答案:

答案 0 :(得分:7)

您可以使用php函数“dechex”将整数转换为Hexa RGB:

http://php.net/manual/en/function.dechex.php

在此页面中有以下功能:

function toColor($n) {
    return("#".substr("000000".dechex($n),-6));
}

未经测试但可以提供帮助。

评论后编辑:您可以在函数中添加一些伪随机函数:

function toColor($n) {
    $n = crc32($n);
    $n &= 0xffffffff;
    return("#".substr("000000".dechex($n),-6));
}

答案 1 :(得分:3)

如果你只是想随机挑选9000种颜色,我想你可以这样做:

$color = substr(md5($number),6);