Extension-based Color Generation

I wanted an algorithm to generate a color based on the extension of a filename (for synthesizing icons for arbitrary files.) After looking around and failing to find anything suitably interesting, I hacked up a solution that I think works pretty well.

It works like this:

  1. Start out with an accumulator and put in constant value that sets some bits. I chose a rather traditional one.
  2. Iterate through the characters of the extension, and XOR the char code value with the accumulator.
  3. Cut down the accumulator to the 0-255 range (mod 256).
  4. Mask and shift the accumulator into three color values: red, blue, and green. The ordering you choose can be arbitrary (I did G, R, and B in that order). Obviously one of the colors will only get two bits (B in my case.)
  5. Multiply the colors so that they fit back into the 0-255 range.
  6. (Depending on usage) combine and convert the three values into hex string notation for HTML/CSS usage.

That's pretty much it. It works well, it's simple, and it produces a reasonable variety of colors.

If you're so inclined you can play with the constants and color ordering to get something that produces "good" colors for certain extensions (blue for Microsoft Word extensions, for example). Obviously given the limited range, you're not gonna wind up with the best colors for everything, and there will be some similarity for otherwise-different extensions, but if your goal is just to get some good variety without hard-coding a bunch of values (or without using an icon set) this'll do it.

I also wanted a good way to isolate the file extension and -- if it's too long for my purposes -- cut it down into a reasonable-looking 3-4 character one. (So ".foobarbaz" would get cut down to something like "fbz".) I've left that in the module too, so feel free to use it if you need to.

Demo / Source

Live Demo

Implementation

License

Public domain. If your country doesn't acknowledge the concept of "public domain", use Creative Commons Zero.