PHP int 到独特的 rgb 颜色


PHP int to unique rgb color

我有数字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;
}

您可以使用 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));
}

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

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