The following class takes a String and converts it to a color.
It is a simplified Java port of the Color-Hash TypeScript project (MIT license): https://github.com/zenozeng/color-hash.
The original project contains some parameters to adjust the generated colours.
These were not included.
The advantage of the Color-Hash algorithm, compared using a hash value directly, is that the generated colours are more perceptually uniform.
A lot of copy/paste was going on here:
Result:
XYZ: #bf40b3
TEST1: #86432d
TEST2: #3a2dd2
TEST3: #bf4073
SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS: #53ac8b
public class ColorHash
{
private static final double[] LigthnessArray = new double[] { 0.35, 0.5, 0.65 };
private static final double[] SaturationArray = new double[] { 0.35, 0.5, 0.65 };
public Color generateColor(String input) throws NoSuchAlgorithmException
{
// Easiest way would be String.hashCode()
// But "Test1" and "Test2" result in practically the same color
// Therefore another hash algorithm should be used
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte[] digest = md.digest();
int hash = Math.abs(ByteBuffer.wrap(digest).getInt());
double hue, saturation, lightness;
hue = hash % 359 / 359.; // note that 359 is a prime
hash = (int) Math.ceil(hash / 360);
saturation = SaturationArray[hash % SaturationArray.length];
hash = (int) Math.ceil(hash / SaturationArray.length);
lightness = LigthnessArray[hash % LigthnessArray.length];
return hslColor((float) hue, (float) saturation, (float) lightness);
}
public String generateColorHash(String input) throws NoSuchAlgorithmException
{
return "#" + Integer.toHexString(generateColor(input).getRGB()).substring(2);
}
private static Color hslColor(float h, float s, float l)
{
float q, p, r, g, b;
if (s == 0)
{
r = g = b = l; // achromatic
} else
{
q = l < 0.5 ? (l * (1 + s)) : (l + s - l * s);
p = 2 * l - q;
r = hue2rgb(p, q, h + 1.0f / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1.0f / 3);
}
return new Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255));
}
private static float hue2rgb(float p, float q, float h)
{
if (h < 0)
{
h += 1;
}
if (h > 1)
{
h -= 1;
}
if (6 * h < 1) { return p + ((q - p) * 6 * h); }
if (2 * h < 1) { return q; }
if (3 * h < 2) { return p + ((q - p) * 6 * ((2.0f / 3.0f) - h)); }
return p;
}
public static void main(String[] args) throws NoSuchAlgorithmException
{
String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};
ColorHash gen = new ColorHash();
for(String p : programs) {
System.out.println(p + ": " + gen.generateColorHash(p));
}
}
}