Turning Strings into Colors

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?

Constraints

  1. Each string had to generate the same color every time
  2. Each color had to feel the same, for lack of a better word
  3. 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:

  1. Input string
  2. Get the string’s MD5 digest
  3. Take the first 3 characters of the digest, a hexadecimal number between 0–4095
  4. Divide this number by 11.4066852368 to get a float between 0–359
  5. Round the float down to the nearest integer and we have our Hue!
  6. 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!

Conclusion

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!

Leave a Reply

Your email address will not be published. Required fields are marked *