PHP generates RGB

I came across a situation where I have an identifier that comes from the database (so it can be 1, 100, 1000, ...), and I need to generate random colors, however an equal ID should lead to the same color.

Any suggestion on how I can achieve this?

Thanks!

+6
source share
4 answers

Use a cryptographic hash and trim bytes that 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 } 

As a result (the code for its creation ) looks like this: numbers 0-20:

demo output

+26
source

The obvious approach is simply to convert the identifier to color (for example, the bottom 8 bits are blue, the next 8 bits are green, the next 8 bits are red - leave 8 bits, but I'm sure you can understand it ;-)

Assuming this doesn't work (because you fall into a terrible color palette: Use an array (or hash table) to map identifiers to colors.

If you are concerned that there are too many identifiers, you can apply some hash to the identifier and use it when entering the "id to color" display. In this case, you are actually saying that one identifier always has one color, but one color can be used by many identifiers.

+1
source
 <?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> 
+1
source

If the array is always sorted, you can use this algorithm with up to 250 elements:

 <?php function getRGBColorString( $array ) { $indexColor = round( 250 / count( $array ) ); $iterator = 1; $arrayOfRGB = array(); foreach( $array as $item) { $arrayOfRGB[] = "rgb(" . ( $indexColor * $iterator ) . ", 113, 113 )"; $iterator++; } return $arrayOfRGB; } ?> 
0
source

Source: https://habr.com/ru/post/907896/


All Articles