4

I am using php's dechex function to generate random colors as per requirements.Here is my working code.

dechex(rand(0x000000, 0xFFFFFF));

Howerver, I want to use dark colors only. I have found this code so far which generated only light colors thanks for this and this article.

However, I am yet to find a proper solution to generate only dark colors. I have tried several things like below.

'#' . substr(str_shuffle('AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899'), 0, 6); 

And

'#' . substr(str_shuffle('ABCDEF0123456789'), 0, 6);

But these, sometimes generating light colors randomly.

Edit:

I would like to have a solution with hex and rgb.

How Can I achieve this ?

Mittul At TechnoBrave
  • 1,142
  • 3
  • 25
  • 70

4 Answers4

2

Here how to get dark color for both Hex and RGB

$hexMin = 0;
$hexMax = 9;
$rgbMin = 0;
$rgbMax = 153; // Hex 99 = 153 Decimal
$hex = '#' . mt_rand($hexMin,$hexMax) . mt_rand($hexMin, $hexMax) . mt_rand($hexMin, $hexMax) . mt_rand($hexMin,$hexMax) . mt_rand($hexMin, $hexMax) . mt_rand($hexMin, $hexMax);
$rgb = 'rgb(' . mt_rand($rgbMin,$rgbMax). ',' . mt_rand($rgbMin,$rgbMax).  ',' . mt_rand($rgbMin,$rgbMax).  ')';
1

Put your HEX to contain only dark colors by limiting max value:

$max = 9;

'#' . mt_rand(0. $max) . mt_rand(0. $max) . mt_rand(0. $max);
Justinas
  • 41,402
  • 5
  • 66
  • 96
1

generate a random color :

function darker_color($rgb, $darker=2) {

    $hash = (strpos($rgb, '#') !== false) ? '#' : '';
    $rgb = (strlen($rgb) == 7) ? str_replace('#', '', $rgb) : ((strlen($rgb) == 6) ? $rgb : false);
    if(strlen($rgb) != 6) return $hash.'000000';
    $darker = ($darker > 1) ? $darker : 1;

    list($R16,$G16,$B16) = str_split($rgb,2);

    $R = sprintf("%02X", floor(hexdec($R16)/$darker));
    $G = sprintf("%02X", floor(hexdec($G16)/$darker));
    $B = sprintf("%02X", floor(hexdec($B16)/$darker));

    return $hash.$R.$G.$B;
}

$color = '#'.dechex(rand(0x000000, 0xFFFFFF));
$dark = darker_color($color);

echo "$color => $dark";

Even if a random generated color is dark , the function pick up a darker color . normaly it goes to black color .

Yassine CHABLI
  • 3,459
  • 2
  • 23
  • 43
1

The main thing you seem to want is to ensure that each pair of hex digits is below a certain level once you've generated a random number. As rand() will generate any value up to the limit, my approach is to keep your original limit of 0xffffff but once the number has been generated, apply a bitwise and (&) to clear the high bits for each byte...

echo '#'.dechex(rand(0x000000, 0xFFFFFF) & 0x3f3f3f);

You can tweak the 0x3f3f3f to a limit which you want to set to limit the maximum value.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55