19 Aug 2013

Repeatable colour generation from arbitrary strings in .NET

I had a need to show items on a web page in different colours. The colours needed to be consistent between page views, but the items came from a database and I didn't want to store colour values in there, or have a hardcoded index of colour values.

A fun solution was to create a string hash using the name of the item, and then use the first three bytes of the string as RGB values to style the item with inline CSS.

var md5Gen = System.Security.Cryptography.MD5.Create();
byte[] hash = md5Gen.ComputeHash(System.Text.Encoding.UTF8.GetBytes(myItem.Name));
string hexColour = string.Format("#{0:X}{1:X}{2:X}", hash[0], hash[1], hash[2]); 
If I helped you out today, you can buy me a beer below. Cheers!