views:

74

answers:

3

I'd like to represent strings as arbitrary html colors.

Example:

"blah blah" = #FFCC00
"foo foo 2" = #565656

It doesn't matter what the actual color code is, so long as it's a valid hexadecimal HTML color code and the whole spectrum is fairly well represented.

I guess the first step would be to do an MD5 on the string and then somehow convert that to hexadecimal color code?

Update: Usage example is to generate a visual report of file requests on a server. The colors don't have to look pretty, it's more so a human brain can detect patterns, etc in the data more readily.

+2  A: 

Almost always, just using random colours will

  1. look bad
  2. conflict with the background

I would recommend creating a (longish) list of colours that work well together and with your background - then just sum the char values of the string and modulus (%) with your number of colours to get an index into the table.

sje397
A: 

I agree with sje397 above that completely random colours could end up looking nasty. Rather than make a long list of nice-looking colours, I would suggest choosing a constant saturation+luminescence value, and varying the hue based on the content. To get an RGB colour from an HSL colour, you may use something similar to what's described in http://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB .

Reinderien
A: 

Thanks for the pointers, this seems to do a competent job:

function stringToColorCode($str) {
  $code = dechex(crc32($str));
  $code = substr($code, 0, 6);
  return $code;
}

$str = 'test123';
print '<span style="background-color:#'.stringToColorCode($str).'">'.$str.'</span>';