PHP generate rgb color to object based on unique value


I know this has been asked before, but I need a little more help than the other answers on SO provide.



I currently have a foreach loop that iterates over records in my DB. Each row contains a unique "id" primary attribute (1,2,3,4,5,etc.).



In my loop, I need to generate a UNIQUE RGB value for each record based on its ID. The resulting RGB value will be applied to the HTML element's text bound to that record. The generated color must be unique to the record itself (via "id"), which is why I am not using the loop iterator.



I have already created a working function to do this for me, but I need one more thing - I need the rgb value to have a contrast ratio greater than 4:5:1 on a white background. The function I have generates colors that are too bright, making the text hard to read. How can I modify my function to produce darker colors that contrast well on a white background?



Maybe this isnt possible... but I'm hoping one of you Math geniuses can help me out :)



You can calculate brightness:



The returned value should be bigger than 5 for best readability.
Function was found here



But you should get another chars from a hash to get another color, so collision more probable.



I believe that a color will be found in 25 cycles :)



While it's a pain to translate, HSV is probably a better color space for this. I like to pick a set Saturation [0.75 is nice] and then play with the Hue and Value.



Lifting the HSV/RGB conversion function from this gist:



And then:



Gives us something like:



yay colored boxes!






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

The Dalles, Oregon

眉山市

清晰法令