0

I have this code:

function rand_colorCode(){
  $r = dechex(mt_rand(0,255));
  $g = dechex(mt_rand(0,255));
  $b = dechex(mt_rand(0,255));
  $rgb = $r.$g.$b;
  if($r == $g && $g == $b){
    $rgb = substr($rgb,0,3);
  }
  return '#'.$rgb;
}

$code = rand_colorCode();

This generates a random color which later gets inserted into the mysql db. But sometimes it generates too light color. (this is a problem because these colors are later displayed and my background color is white)

My simple question is: How can I prevent colors being too light or too dark? How should I customize my code?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Akos
  • 1,997
  • 6
  • 27
  • 40
  • I suggest you re-evaluate your approach. Using a limit - 50-200 instead of 0,255 - would eliminate red(255,0,0), green(0,255,0) and blue(0,0,255) from possible generated colors. – Luchian Grigore Oct 28 '11 at 13:57

3 Answers3

2

Use a shorter color range:

mt_rand(80,200)

The lower boundary prevents near-black colors, while the higher boundary prevents near-white colors. You can adjust this range to suit your needs.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
2

You can calculate the brightness of the current set of colors and validate it according to some predefined limits:

while ( true )
{
  $r = dechex(mt_rand(0,255));
  $g = dechex(mt_rand(0,255));
  $b = dechex(mt_rand(0,255));
  $brightness = ( 0.2126 * $r ) + ( 0.7152 * $g ) + ( 0.0722 * $b )
  if ( $brightness > $lower_limit || $brightness < $upper_limit )
     break;
}

The formula is taken from here Formula to determine brightness of RGB color

Community
  • 1
  • 1
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

Well the RGB code of (for instance) white is 255, 255, 255. You can just define a rule that if all three values (R, G & B) are above a certain treshold, the color will be too light and will thus not display correctly. Try to define a treshold yourself by having a look at a color palet. Maybe 200, 200, 200 would be the maximum you'd want and 50, 50, 50 the minimum.

You can then just randomize a color from 50 up to 200 (if you define that as your treshold). So instead of

 $r = dechex(mt_rand(0,255)); 

You do

 $r = dechex(mt_rand(50,200)); 

This could be an easy way to fix it.

Jules
  • 7,148
  • 6
  • 26
  • 50
  • This would exclude pure colors like 0,0,255; 0,255,0; 255,0,0 which are blue, green and red and has nothing to do with a black/white background. – Luchian Grigore Oct 28 '11 at 13:55