开发者

Random color generation using PHP

I'm trying to generate random HTML colors in PHP, but I'm having trouble getting them to look similar, or in the same family. Is there some function I can use to开发者_StackOverflow generate colors that are "similar" to another color, besides just generating and concatenating 6 random hex digits?


You could

  1. Generate one random decimal number betweem 25 and 230 (your "base" number)
  2. Generate 3 random numbers between 1 and 25 (arbitrarily deciding whether they will be positive or negative)
  3. Add those three numbers to your base number to get three different numbers (your R, G, and B)
  4. Repeat steps 2 and 3 to get more, similar colors

You could widen the range of the modifier number (the one from 1 to 25) to get more variance in your color (you'd have to change the range of your base number as well, so you stay between 0 and 255).

I don't know anything about PHP, which is why I'm not putting code. But I thought it was an interesting question =)

EDIT: I realized that generating 3 random base numbers in step 1 will get you a less muted looking (grey) color. Then you can follow steps 2 and 3 to get different shades etc. as I already mentioned (and, as @Peter mentioned, increasing the modifier number at the risk of getting less "similar" colors)

Example output of this technique (based on two different sets of base numbers):

Random color generation using PHP

EDIT 2: Here is the PHP implementation of this by @Peter Ajtai

<?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/>";
}
?>


Found something much nicer posted on the blog of someone called Craig Lotter:

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


a convoluted class i wrote based on colors sharing a brightness. closer the range, greyer the colors. higher the range, brighter the colors.

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);
    }
}


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;}


you can make your own function which will generate your own rgb color

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(); 
?>

or bgcolor

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(); 
?>


A few years ago I came across this class. It lets you generate complimentary colors based on a seed value.

If you're looking for something more general, limit yourself to a general range using rand (obviously below 255) and the use base_convert.


I'd just limit the range of the 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>';
}


RandomColor has been ported to PHP, you can find it here. With it it's also possible to have random light or random dark colors.
Example Usage:

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'
));


Another short and simple version: change the mt_rand(X, Y) values in order to generate desired colour range: (0, 255) - full range; (180, 255) - pastel palette; (0, 100) - dark palette; etc...

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;
}


Try this:

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

And than you can just use it like this:

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


If you want to create similar looking colors, it would be easier to use HSV instead of RGB, but you'll need to convert between them.

PHP HSV to RGB formula comprehension

and / or

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

In ordet to get similar colors, you 'fix' 2 of three components and create random values for the third, for example:

function random_color(){

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


This might help sprintf("%06s\n", strtoupper(dechex(rand(0,10000000))));


<?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)";
}


I used this example was very useful and easy, it helped a lot. If someone needs the links and example.

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)'
));

See the results on the demo. https://www.strangeplanet.fr/work/RandomColor.php/

And packagist with composer https://packagist.org/packages/mistic100/randomcolor

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜