Code Scraps: Random unique colour generation

I have worked on a number of social projects over the years which have involved message boards or social posting features by users.  On some websites like Microsoft’s message boards or StackOverflow as part of their profile when accounts are first created, users get assigned randomly generated unique icons or imagery. I have always tried to do similar things when creating social projects, to ensure that each user is visually unique to another by means of a uniquely generated image or colour.

TL:DR;
Here’s a quick and simple notation of the code block below and how a random unique colour is created:
md5(time())=60C827C2A5854AB99392B82EC871DE46
60C8+27C2+A585+4AB9+9392+B82E+C871+DE46=46B3F
str_pad(46B3F,0,LEFT)=#046B3F

The Code

The following is a snip of code to generate a short code which I have used in the past to create a default name highlight or text colour for a user.

This code block is in PHP – but can be adapted to any language

// Get a unique hash (The parameter can be anything – time() used in this case).
$hash = md5(time());
// Inject separators into the string (just a quick way to chunk the string to 4 characters)
for ($i = 4; $i < 32; $i+=4) { $hash = substr_replace($hash, “,”, $i, 0); }
$sum = explode(“,”, $hash);
$total = 0;
// Sum all the chunks (we convert them to decimal to make sure PHP casts them correctly to a numeric value).
for ($i = 0; $i < count($sum); $i++) { $total += hexdec($sum[$i]); }
// Get the Hexidecimal value of the total
$hex = dechex($total);
// If the resulting hex is shorter than 6 characters, pad it with leading zeros.
if (strlen($hex)<6) { $hex = str_pad($hex, 6, “0”, STR_PAD_LEFT); }
// Else if it’s longer than 6, shave off the excess and add it back.
else {
// We do this as a loop as we might have a situation where adding the excess makes it longer than 6 too.
$k = 0;
while (strlen($hex)>6) {
$extra = substr($hex,6);
$hex = hexdec(substr($hex,0,6));
$hex += $extra;
$hex = dechex($hex);
$k++;
// If we’ve hit this, we ended up wih a runaway loop. Kill the loop to continue.
if ($k > 100) { $hex = substr($hex,0,6); }
}
}

echo “<span style=\”display:block;width:100px;height:100px;background:#”.$hex.”;\”></span>”;

The code block above results in this example. Please note that this example is behind a cache, so please use CTRL+F5 to see the colour change after a second (as PHP’s time() returns seconds not milliseconds like other languages). Or if the cache is being particularly persistant and won’t change, append the URL with a query string eg: ?count=1  (then increment your count for each refresh you want to do).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.