【问题标题】:Random color generation using PHP使用 PHP 随机生成颜色
【发布时间】:2011-11-07 22:53:42
【问题描述】:

我正在尝试在 PHP 中生成随机的 HTML 颜色,但我无法让它们看起来相似或属于同一个系列。除了生成和连接 6 个随机十六进制数字之外,是否有一些函数可以用来生成与另一种颜色“相似”的颜色?

【问题讨论】:

  • 类似颜色的例子?
  • 是的,类似的意思是什么?亮度范围?光谱范围?
  • 想象一盒蜡笔,我在想像所有浅色的东西,例如浅蓝色、浅绿色等,或所有“褪色”的颜色。我不是 100% 确定这里的技术术语,但希望能回答您的问题。

标签: php html colors


【解决方案1】:

你可以

  1. 生成一个介于 25 和 230 之间的随机十进制数(您的“基数”)
  2. 生成 3 个 1 到 25 之间的随机数(任意决定它们是正数还是负数)
  3. 将这三个数字与您的基数相加,得到三个不同的数字(您的 R、G 和 B)
  4. 重复第 2 步和第 3 步以获得更多相似的颜色

您可以扩大修饰符编号的范围(从 1 到 25)以获得更多的颜色变化(您还必须更改基数的范围,因此您保持在 0 到 255 之间)。

我对PHP一无所知,这就是我不放代码的原因。但我认为这是一个有趣的问题 =)

编辑:我意识到在第 1 步中生成 3 个随机基数将使您的颜色看起来不那么柔和(灰色)。然后你可以按照步骤 2 和 3 来获得不同的色调等,正如我已经提到的(并且,正如@Peter 提到的,增加修饰符的数量有可能获得更少的“相似”颜色)

此技术的示例输出(基于两组不同的基数):

编辑 2:这是@Peter Ajtai 的 PHP 实现

<?php
$spread = 25;
for ($row = 0; $row < 100; ++$row) {
        for($c=0;$c<3;++$c) {
        $color[$c] = rand(0+$spread,255-$spread);
    }
    echo "<div style='float:left; background-color:rgb($color[0],$color[1],$color[2]);'>&nbsp;Base Color&nbsp;</div><br/>";
    for($i=0;$i<92;++$i) {
    $r = rand($color[0]-$spread, $color[0]+$spread);
    $g = rand($color[1]-$spread, $color[1]+$spread);
    $b = rand($color[2]-$spread, $color[2]+$spread);    
    echo "<div style='background-color:rgb($r,$g,$b); width:10px; height:10px; float:left;'></div>";
    }    
    echo "<br/>";
}
?>

【讨论】:

  • 我现在远离我的电脑,但我意识到这可能只会产生随机的灰色阴影 =/ 存在感。
  • 灰色,但并非完全灰色。您可以增加 25 以减少灰色,但它们的“相关性”较少 - 我认为您的方法基本上是这里的第五个 ==> codepad.viper-7.com/tCtTdb
  • @Peter 感谢您的确认,我担心我完全搞砸了哈哈。我已经通过稍微修改和实际技术的屏幕截图更新了答案 - 我将其编码为C#,而不是PHP =)
  • @Rich D:如果您希望我发布 C# 代码(这样您就可以大致了解要做什么,然后将其转换为 PHP),请告诉我。祝你好运!
  • @Rich - (@jadarnel - 这是一种有趣的方式)它在 PHP 中。只需更改$spread 即可扩大或缩小范围。 ==> codepad.viper-7.com/lYj9Hp(显示 100 种基色和一行“相关”颜色)
【解决方案2】:

在the blog of someone called Craig Lotter:上发现了一些更好的帖子

$randomcolor = '#' . dechex(rand(0,10000000));

【讨论】:

  • 对于 CSS 我们可以使用更严格的命令:'#' . dechex(rand(256,16777215))。这将在#100 和#ffffff 之间生成十六进制颜色。
【解决方案3】:

我基于共享亮度的颜色编写的复杂类。范围越近,颜色越灰。范围越高,颜色越亮。

class colorGenerator
{

    protected $rangeLower, $rangeHeight;
    private $range = 100;

    function __construct($range_lower = 80, $range_higher = 160)
    {
        // range of rgb values
        $this->rangeLower  = $range_lower;
        $this->rangeHeight = $range_higher - $range_lower;
    }

    protected function randomColor()
    {
        // generate random color in range
        return $this->generateColor(rand(0, 100));
    }

    protected function generateColor($value)
    {
        // generate color based on value between 0 and 100
        // closer the number, more similar the colors. 0 is red. 50 is green. 100 is blue.
        $color_range  = $this->range / 3;
        $color        = new stdClass();
        $color->red   = $this->rangeLower;
        $color->green = $this->rangeLower;
        $color->blue  = $this->rangeLower;
        if ($value < $color_range * 1) {
            $color->red += $color_range - $value;
            $color->green += $value;
        } else if ($value < $color_range * 2) {
            $color->green += $color_range - $value;
            $color->blue += $value;
        } else if ($value < $color_range * 3) {
            $color->blue += $color_range - $value;
            $color->red += $value;
        }
        $color->red = round($color->red);
        $color->blue = round($color->blue);
        $color->green = round($color->green);
        // returns color object with properties red green and blue.
        return $color;
    }

    protected function RGBColor($stdClass)
    {
        $RGB = "rgb({$stdClass->red}, {$stdClass->blue}, {$stdClass->green})";
        return $RGB;
    }

    function CreateColor($value) {
        $stdClass = $this->generateColor($value);
        return $this->RGBColor($stdClass);
    }

    function CreateRandomColor($value) {
        $stdClass = $this->randomColor($value);
        return $this->RGBColor($stdClass);
    }
}

【讨论】:

    【解决方案4】:
    function randomColor() {
    $str = '#';
    for ($i = 0; $i < 6; $i++) {
        $randNum = rand(0, 15);
        switch ($randNum) {
            case 10: $randNum = 'A';
                break;
            case 11: $randNum = 'B';
                break;
            case 12: $randNum = 'C';
                break;
            case 13: $randNum = 'D';
                break;
            case 14: $randNum = 'E';
                break;
            case 15: $randNum = 'F';
                break;
        }
        $str .= $randNum;
    }
    return $str;}
    

    【讨论】:

      【解决方案5】:

      你可以制作你自己的函数来生成你自己的rgb颜色

      http://sandbox.phpcode.eu/g/bf2a5/1

      <?php  
      function gen(){ 
          for($i=1;$i<200;$i++){ 
             echo "<div style='color:rgb($i,$i,0);'>hello</div>"; 
          } 
      } 
      
      gen(); 
      ?>
      

      或背景色

      http://sandbox.phpcode.eu/g/bf2a5/2

      <?php  
      function gen(){ 
          for($i=1;$i<200;$i++){ 
             echo "<div style='background-color:rgb($i,$i,0);'>hello</div>"; 
          } 
      } 
      
      gen(); 
      ?>
      

      【讨论】:

      • 这基本上是我已经在做的,并且生成的颜色不能很好地协同工作。
      • 这不是随机的。它只是一堆红色/绿色的连续阴影。
      • @MarcB: 我认为 $i 可以是 rand()omed
      • 那么你又回到了 OP 的船,拥有非常不同的随机颜色 - OP 想要颜色相对相同(浅棕色 + 深棕色,而不是粉红色 + 草)。
      • @MarcB:我的意思是 for() 中的 $i 可以被 rand()omized
      【解决方案6】:

      几年前我遇到了this class。它可以让您根据种子值生成互补色。

      如果您正在寻找更通用的东西,请使用rand(显然低于255)将自己限制在一个通用范围内,并使用base_convert。

      【讨论】:

        【解决方案7】:

        我只是限制 rand()-params 的范围:

        // full color palette (32 bit)
        for($index = 0; $index < 30; $index++)
        {
            echo '<div style="background-color: #' . dechex(rand(0,16777215)) . '; display: inline-block; width: 50px; height: 50px;"></div>';
        }
        echo '<br />';
        
        // pastell colors
        for($index = 0; $index < 30; $index++)
        {
            echo '<div style="background-color: rgb(' . rand(128,255) . ',' . rand(128,255) . ',' . rand(128,255) . '); display: inline-block; width: 50px; height: 50px;"></div>';
        }
        echo '<br />';
        
        // dark colors
        for($index = 0; $index < 30; $index++)
        {
            echo '<div style="background-color: rgb(' . rand(0,128) . ',' . rand(0,128) . ',' . rand(0,128) . '); display: inline-block; width: 50px; height: 50px;"></div>';
        }
        echo '<br />';
        
        // shades of blue
        for($index = 0; $index < 30; $index++)
        {
            echo '<div style="background-color: rgb(' . rand(0,56) . ',' . rand(0,56) . ',' . rand(0,255) . '); display: inline-block; width: 50px; height: 50px;"></div>';
        }
        echo '<br />';
        
        // shades of green
        for($index = 0; $index < 30; $index++)
        {
            echo '<div style="background-color: rgb(' . rand(0,56) . ',' . rand(0,255) . ',' . rand(0,56) . '); display: inline-block; width: 50px; height: 50px;"></div>';
        }
        echo '<br />';
        
        // shades of red
        for($index = 0; $index < 30; $index++)
        {
            echo '<div style="background-color: rgb(' . rand(0,255) . ',' . rand(0,56) . ',' . rand(0,56) . '); display: inline-block; width: 50px; height: 50px;"></div>';
        }
        

        【讨论】:

          【解决方案8】:

          RandomColor 已移植到 PHP,您可以找到它here。有了它,还可以有随机的 light 或随机的 dark 颜色。
          示例用法:

          include('RandomColor.php');
          use \Colors\RandomColor;
          // Returns a hex code for a 'truly random' color
          RandomColor::one(array(
             'luminosity' => 'random',
             'hue' => 'random'
          ));
          // Returns a hex code for a light blue
          RandomColor::one(array(
             'luminosity' => 'light',
             'hue' => 'blue'
          ));
          

          【讨论】:

            【解决方案9】:

            另一个简短的版本: 更改 mt_rand(X, Y) 值以生成所需的颜色范围:(0, 255) - 全范围; (180, 255) - 柔和的调色板; (0, 100) - 深色调色板;等等……

            function gen_color(){
                mt_srand((double)microtime()*1000000); 
                $color_code = '';
                while(strlen($color_code)<6){
                    $color_code .= sprintf("%02X", mt_rand(0, 255));
                }
                return $color_code;
            }
            

            【讨论】:

              【解决方案10】:

              试试这个:

              //For every hex code
              $random = mt_rand(0, 16777215);
              $color = "#" . dechex($random);
              

              你可以像这样使用它:

              background-color: <?php echo $color ?>;
              

              【讨论】:

                【解决方案11】:

                如果您想创建外观相似的颜色,使用 HSV 而不是 RGB 会更容易,但您需要在它们之间进行转换。

                PHP HSV to RGB formula comprehension

                和/或

                http://www.brandonheyer.com/2013/03/27/convert-hsl-to-rgb-and-rgb-to-hsl-via-php/

                为了获得相似的颜色,您“修复”三个组件中的 2 个并为第三个创建随机值,例如:

                function random_color(){
                
                    // random hue, full saturation, and slightly on the dark side
                    return HSLtoRGB(rand(0,360), 1, 0.3);
                }
                

                【讨论】:

                  【解决方案12】:

                  这可能有助于sprintf("%06s\n", strtoupper(dechex(rand(0,10000000))));

                  【讨论】:

                    【解决方案13】:
                    <?php 
                    function randomColor(){
                        $rand1 = mt_rand(0, 255);
                        $rand2 = mt_rand(0, 255);
                        $rand3 = mt_rand(0, 255);
                        return "rgb(".$rand1.",".$rand2.",".$rand3.", 0.3)";
                    }
                    

                    【讨论】:

                    • 请也写一些解释。
                    • 这不能回答所提出的问题。在用现有答案回答旧问题时,请务必指出您的答案所针对的问题的新方面。答案应包括对其工作方式和原因的解释。
                    【解决方案14】:

                    我使用的这个例子非常有用且简单,它帮助很大。如果有人需要链接和示例。

                    use \Colors\RandomColor;
                    
                    // Returns a hex code for an attractive color
                    RandomColor::one(); 
                    
                    // Returns an array of ten green colors
                    RandomColor::many(10, array(
                       'hue' => 'green'
                    ));
                    
                    // Returns a hex code for a light blue
                    RandomColor::one(array(
                       'luminosity' => 'light',
                       'hue' => 'blue'
                    ));
                    
                    // Returns one yellow or blue color
                    RandomColors::one(array(
                        'hue' => array('yellow', 'blue')
                    ));
                    
                    // Returns a hex code for a 'truly random' color
                    RandomColor::one(array(
                       'luminosity' => 'random',
                       'hue' => 'random'
                    ));
                    
                    // Returns a bright color in RGB
                    RandomColor::one(array(
                       'luminosity' => 'bright',
                       'format' => 'rgbCss' // e.g. 'rgb(225,200,20)'
                    ));
                    

                    在演示中查看结果。 https://www.strangeplanet.fr/work/RandomColor.php/

                    和作曲家的打包师 https://packagist.org/packages/mistic100/randomcolor

                    【讨论】:

                      猜你喜欢
                      • 2013-04-02
                      • 2017-01-29
                      • 1970-01-01
                      • 2013-01-07
                      • 2015-06-15
                      • 1970-01-01
                      • 2011-08-02
                      • 2015-11-07
                      • 2012-02-19
                      相关资源
                      最近更新 更多