Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP generate RGB

I'm facing this situation where I have an ID which comes from a database (so it can be 1, 100, 1000, ...) and I need to generate random colors, however equal ID's should result in the same color.

Any suggestion on how I can achieve this?

Thanks!

like image 702
user485659 Avatar asked Feb 08 '12 00:02

user485659


2 Answers

Use a cryptographic hash and clip the bytes you don't need:

function getColor($num) {
    $hash = md5('color' . $num); // modify 'color' to get a different palette
    return array(
        hexdec(substr($hash, 0, 2)), // r
        hexdec(substr($hash, 2, 2)), // g
        hexdec(substr($hash, 4, 2))); //b
}

The resulting (code to generate it) looks like this for the numbers 0-20:

demo output

like image 112
phihag Avatar answered Oct 02 '22 01:10

phihag


<?php 
// someting like this?
$randomString = md5($your_id_here); // like "d73a6ef90dc6a ..."
$r = substr($randomString,0,2); //1. and 2.
$g = substr($randomString,2,2); //3. and 4.
$b = substr($randomString,4,2); //5. and 6.
?>
<style>
#topbar { border-bottom:4px solid #<?php echo $r.$g.$b;  ?>; }
</style>
like image 28
P_95 Avatar answered Oct 02 '22 01:10

P_95