【问题标题】:PHP int to unique rgb color [closed]PHP int 到唯一的 rgb 颜色 [关闭]
【发布时间】:2012-06-15 02:53:40
【问题描述】:

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

【问题讨论】:

  • RGB 码实际上是 24 位整数,表示为十六进制,所以应该没问题。事实上,如果你可以扩大合同范围,使它们介于 0 和(2 ^ &lt;a mutliple of 8&gt;) - 1 之间,那么0 -&gt; (2 ^ 8) - 10 -&gt; (2 ^ 16) - 10 -&gt; (2 ^ 24) - 1 会容易得多——你可以这样做吗?

标签: php colors int rgb


【解决方案1】:

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

【讨论】:

  • 这也会产生非常相似的颜色——它们总是很蓝,有时有点绿,但在指定范围内不会有任何红色。
  • 太棒了!这似乎是我一直在寻找的。 Akarun,你确定输出中没有重复的颜色吗?
  • 测试过了。似乎在我的 1000 - 9999 范围内是独一无二的。太好了!
【解决方案2】:

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

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

【讨论】:

  • +1 这一点也不坏。轻微的碰撞风险,但可能不足以使其成为严重问题。
  • +1 但它是substr(md5($number), -6)substr(md5($number), 0, 6)
猜你喜欢
  • 2011-12-22
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
  • 2013-03-26
  • 2015-06-16
相关资源
最近更新 更多