16

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 generate colors that are "similar" to another color, besides just generating and concatenating 6 random hex digits?

Rich Darvins
  • 351
  • 2
  • 4
  • 9
  • An example for the similar colors? – Tarik Aug 31 '11 at 20:44
  • Yeah, what do you mean similar? brightness range? spectrum range? – dqhendricks Aug 31 '11 at 20:48
  • Imagine a box of crayons, I'm thinking something like all the light colors e.g. Light Blue, Light Green, etc., or all the "faded" colors. I'm not 100% sure of the technical terms here but hopefully that answers your questions. – Rich Darvins Aug 31 '11 at 20:53

14 Answers14

23

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, similar colors

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/>";
}
?>
Josh Darnell
  • 11,304
  • 9
  • 38
  • 66
  • Im away from my pc now, but just realized that this might just generate random shades of grey =/ how existential. – Josh Darnell Aug 31 '11 at 21:16
  • Grayish, but not entirely gray. You can increase 25 for less grayish, but then they're less "related" - I think your method is basically the fifth one down here ==> http://codepad.viper-7.com/tCtTdb – Peter Ajtai Aug 31 '11 at 21:29
  • @Peter Thanks for confirming, I was concerned I totally goofed haha. I've updated the answer with a slight modification and a screenshot of the technique in action - I coded it in `C#`, not `PHP` though =) – Josh Darnell Sep 01 '11 at 04:42
  • @Rich D: If you'd like me to post the C# code (so you can have a basic outline of what to do, then convert it to PHP) let me know. Good luck! – Josh Darnell Sep 01 '11 at 14:23
  • 1
    @Rich - (@jadarnel - this is a fun way to do it) Here it is in PHP. Just change `$spread` to broaden or narrow the spectrum. ==> http://codepad.viper-7.com/lYj9Hp (shows 100 base colors and a row of "related" colors) – Peter Ajtai Sep 01 '11 at 18:47
20

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

$randomcolor = '#' . dechex(rand(0,10000000));
Max
  • 12,794
  • 30
  • 90
  • 142
  • 5
    For CSS we can use more strict command: `'#' . dechex(rand(256,16777215))`. This will generate hex-color between #100 and #ffffff. – Paul Annekov Oct 22 '13 at 10:59
  • This is a great one-liner and I'm all about one-liners. But sometimes it returns a non-color result with a reasonably moderate probability, so I converted it to a recursive function. If the result is not seven characters long, it calls itself until it is. – DanimalReks Dec 15 '22 at 18:08
4

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);
    }
}
classicjonesynz
  • 4,012
  • 5
  • 38
  • 78
dqhendricks
  • 19,030
  • 11
  • 50
  • 83
3
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;}
2

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(); 
?>
genesis
  • 50,477
  • 20
  • 96
  • 125
2

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.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
1

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'
));
Clawish
  • 2,934
  • 3
  • 24
  • 28
1

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;
}
Muscaria
  • 129
  • 1
  • 3
1

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 ?>;
ase
  • 13,231
  • 4
  • 34
  • 46
1

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>';
}
feeela
  • 29,399
  • 7
  • 59
  • 71
0

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);
}
Community
  • 1
  • 1
Ideogram
  • 1,265
  • 12
  • 21
0

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

heshanlk
  • 333
  • 3
  • 9
0
<?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)";
}
  • 4
    Please write some explanation too. – sauhardnc Jun 24 '20 at 15:56
  • 3
    This does not answer the question that was asked. When answering older questions with existing answers be sure to point out what new aspect of the question your answer addresses. Answers should include explanations of how and why they work. – Jason Aller Jun 24 '20 at 16:26
0

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