Gerben Jacobs
Gerben Jacobs

Reputation: 4583

Change random strings into colours, consistently

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.

Upvotes: 9

Views: 5433

Answers (3)

bdb.jack
bdb.jack

Reputation: 147

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 ) ) );

Upvotes: 1

radha krishna
radha krishna

Reputation: 1

first convert random string into hexadecimal number with 6 digits and remove the floats and make the string into integer and convert them into a hexadecimal string and then put a hash before six digit hexadecimal number and there is a color for that random string and you may find hexadecimal number be more than a six digit one , if so , continue dividing that number with 2 till it becomes 5 digit hexadecimal number and the sixth digit will be the number of time the total hexadecimal number divided by 2, there is your color code.

Upvotes: -1

Chris Wesseling
Chris Wesseling

Reputation: 6368

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);
}
?>

Upvotes: 30

Related Questions