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!
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:
<?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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With