GGio
GGio

Reputation: 7653

Generate high contrast random color using PHP

I need to generate random colors for all the users in the system. The trick is that 2 users cant have very similar colors, they need to be distinguishable. I have the code to generate random colors given the original mix color but cant find a way to generate random colors with high contrast using only PHP

public static function generateRandomColor($rgb)
{
    $red = rand(1, 256);
    $green = rand(1, 256);
    $blue = rand(1, 256);

    if (! empty($rgb))
    {
        $red = ($red + $rgb['red']) / 2;
        $green = ($green + $rgb['green']) / 2;
        $blue = ($blue + $rgb['blue']) / 2;
    }

    $color = "rgb({$red}, {$green}, {$blue})";

    return $color;
}

and then i have a loop:

$colorsArr = array();
$mixed = array('red' => 255, 'green' => 255, 'blue' => 255);
for($i = 0; $i < count($users); $i++)
{
    $color = generateRandomColor($mixed);

    $colorsArr .= '<div style="width:25px; height: 25px; background-color: ' . $color . '"></div>';
}

now this generates colors but some colors look like each other. The goal is to have an unique color for each user. any help appreciated thanks.

NOTE: i do not want to hardcode the colors for 500 users

Upvotes: 0

Views: 5567

Answers (1)

Sammitch
Sammitch

Reputation: 32262

I got bored, here's some code you can dink around with:

<?php
define( COL_MIN_AVG, 64 );
define( COL_MAX_AVG, 192 );
define( COL_STEP, 16 );

// (192 - 64) / 16 = 8
// 8 ^ 3 = 512 colors

function usercolor( $username ) {
        $range = COL_MAX_AVG - COL_MIN_AVG;
        $factor = $range / 256;
        $offset = COL_MIN_AVG;

        $base_hash = substr(md5($username), 0, 6);
        $b_R = hexdec(substr($base_hash,0,2));
        $b_G = hexdec(substr($base_hash,2,2));
        $b_B = hexdec(substr($base_hash,4,2));

        $f_R = floor((floor($b_R * $factor) + $offset) / COL_STEP) * COL_STEP;
        $f_G = floor((floor($b_G * $factor) + $offset) / COL_STEP) * COL_STEP;
        $f_B = floor((floor($b_B * $factor) + $offset) / COL_STEP) * COL_STEP;

        return sprintf('#%02x%02x%02x', $f_R, $f_G, $f_B);
}

for( $i=0; $i<30; $i++ ) {
        printf('<div style="height: 100px; width: 100px; background-color: %s">&nbsp;</div>'."\n", usercolor(rand()));
}

Many colors will look pretty similar, but the chances that they'll be right next to each other are slim.

Upvotes: 4

Related Questions