I've needed to do this a couple of times, so I guess it's time to save it as a Gist for next time.
What I needed was a way to calculate a color based on string contents, where the same string would always generate the same color. I also wanted the colors generated to be part of the web safe palette. Not that there's any reason to stay in that palette for browsers now, but I wanted to keep the possible palette relatively small and have colors that generally look okay together. The math behind the web safe palette made it pretty easy.
As it works out, all of the web safe colors are multiples of 51. We'll need that bit of trivia in a second...
First thing I did was get the md5 hash of the string so the code has a string of hexadecimal characters to work with. The first 2 hex characters become the red value, the next 2 are green, and the next 2 are blue. Those are then converted to decimal to make the math easier.
Using a formula that I found on Stack Overflow each number is rounded to the nearest
multiple of 51. Since the largest hex value would be ff
I didn't have to worry about overflowing.
A bit of sprintf to format, and it'll kick out the hex code that I needed.
If I hadn't wanted to stay within the web safe palette, this would have been much shorter. I would have just taken the first
6 characters from the md5
hash and added a #
to the front.