Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random color generation using PHP

Tags:

html

php

colors

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?

like image 413
Rich Darvins Avatar asked Aug 31 '11 20:08

Rich Darvins


People also ask

How to set random color in PHP?

php $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); $color = '#'. $rand[rand(0,15)].

What is random color hex?

The colors are generated with true randomness originating from atmospheric noise. Hexadecimal color codes are used to represent colors numerically as three values in the [0,255] range: red, green and blue. The greater each value, the higher the intensity of the corresponding component.


1 Answers

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/>";
}
?>
like image 190
Josh Darnell Avatar answered Sep 21 '22 13:09

Josh Darnell