Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change random strings into colours, consistently

Tags:

php

I have some IDs that I want to generate random colours for. Making random colours is not the issue, but it has to be consistent.

I could MD5 (or some other kind of hash) the IDs so the code could know how much characters to expect, but the bottomline is it has to generate the same (random) colour for the same ID/hash/string.

like image 706
Gerben Jacobs Avatar asked Mar 29 '13 13:03

Gerben Jacobs


People also ask

How to randomize color in CSS?

There is no way to do this using CSS only. CSS doesn't support logical statements because CSS is purely deterministic (there is nothing like array etc in CSS). We can use client-side JavaScript to select a random color from the array.


2 Answers

All you need for a RGB code is a consistent mapping from your random string to a 6 position hex value. Why not use md5 as a way to a hex string, and then take the first 6 digits?

<?php
function rgbcode($id){
    return '#'.substr(md5($id), 0, 6);
}
?>
like image 124
Chris Wesseling Avatar answered Sep 28 '22 04:09

Chris Wesseling


Here's a simple function that I'm using in one of my own projects to create RGB values which I can use with PHP's imagecolorallocatealpha:

function randomRgbGeneratorFromId( $id = null ) {
    $md5 = md5( $id );
    $md5 = preg_replace( '/[^0-9a-fA-F]/', '', $md5 );
    $color = substr( $md5, 0, 6 );
    $hex = str_split( $color, 1 );
    $rgbd = array_map( 'hexdec', $hex );
    $rgba = array(
        ( $rgbd[0] * $rgbd[1] ),
        ( $rgbd[2] * $rgbd[3] ),
        ( $rgbd[4] * $rgbd[5] ),
    );
    return $rgba;
}

Of course you can always output to your CSS / HTML by using something like this:

  echo sprintf( 'rgb(%s)', implode( ',', randomRgbGeneratorFromId( $id ) ) );
like image 24
bdb.jack Avatar answered Sep 28 '22 06:09

bdb.jack