Recently I had to find a way to turn strings into colors — it was an interesting problem and this is how I solved it.
Why turn Strings into Colors?
Whilst building a small app which involved lots of (grey and boring) charts, I thought “Wouldn’t it be nice if each chart had a different color”. I didn’t fancy adding the ability for users to select a color for each one manually (and let them choose its size, and whether it’s 3D, and whether it’s resizeable, and featurebloat ad infinitum). Each chart had a title, so could I make the decision automatic based on that?
- Each string had to generate the same color every time
- Each color had to feel the same, for lack of a better word
- It must be possible to control the feel of all generated colors
How to turn Strings into Colors
Quite easily, actually. To solve point #1: MD5, and to solve points #2 and #3: HSL.
Here’s how it works:
- Input string
- Get the string’s MD5 digest
- Take the first 3 characters of the digest, a hexadecimal number between 0–4095
- Divide this number by 11.4066852368 to get a float between 0–359
- Round the float down to the nearest integer and we have our Hue!
- Saturation and Lightness default to 50 (out of 100) but can be changed
// MD5 the string $this->hue = md5($this->string); // Take the first 3 chars (hex value between 0–4095) $this->hue = substr($this->hue,0,3); // Convert hex to decimal int $this->hue = hexdec($this->hue); // Divide to get float between 0–359 $this->hue = $this->hue / 11.4066852368; // Round down to nearest int $this->hue = round($this->hue);
As for generating colors that felt the same and being able to change the feel (I promise I’ll stop saying “feel” now) being able to control the Saturation and Lightness and making them consistent between generations, unless changed by programmer, meant that you wouldn’t have a bright, saturated red next to a dull and dark blue.
If the output needs to be in Hex or RGB, divide Hue by 360 then Saturation and Lightness by 100 (so they’re all between 0–1) and run through an HSL to RGB function. Converting from RGB to Hex, if needed, is just changing the base, so pick your format and return!
Shockingly simple now you know how it’s done, but quite useful. Whenever a chart needs a color, a header needs a
text-shadow or a button needs a background, let PHP do the work instead of adding unnecessary customisation features and turn strings into colors!