Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute hex color code for an arbitrary string

Heading

Is there a way to map an arbitrary string to a HEX COLOR code. I tried to compute the HEX number for string using string hashcode. Now I need to convert this hex number to six digits which are in HEX color code range. Any suggestions ?

String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};

for(int i = 0; i < programs.length; i++) {
  System.out.println( programs[i] + " -- " + Integer.toHexString(programs[i].hashCode()));
}
like image 710
tech20nn Avatar asked Mar 17 '10 18:03

tech20nn


3 Answers

If you don't really care about the "meaning" of the color you can just split up the bits of the int (remove the first for just RGB instead of ARGB)

String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};

for(int i = 0; i < programs.length; i++) {
  System.out.println( programs[i] + " -- " + intToARGB(programs[i].hashCode()));
}
....
public static String intToARGB(int i){
    return Integer.toHexString(((i>>24)&0xFF))+
        Integer.toHexString(((i>>16)&0xFF))+
        Integer.toHexString(((i>>8)&0xFF))+
        Integer.toHexString((i&0xFF));
}
like image 135
M. Jessup Avatar answered Sep 20 '22 04:09

M. Jessup


I ran into this question while looking for a Ruby solution, so I thought I would add an answer for Ruby in case someone follows the same path I did. I ended up using the following method, which creates the same six digit hex code from a string by using String.hash and the optional base-specifying parameter of Fixnum.to_s. It slices from 1 rather than 0 to skip negative signs.

def color_from_string(query)
  '#'+query.hash.to_s(16).slice(1,6)
end
like image 32
NealJMD Avatar answered Sep 21 '22 04:09

NealJMD


How about anding the hashcode with 0x00FFFFFF (or 0xFFFFFF if you want to default the alpha channel)? For example:

private String getColorCode(String inputString)
{
    String colorCode = String.format("#%06x", 0xFFFFFF & inputString.hashCode());
}
like image 21
codaddict Avatar answered Sep 21 '22 04:09

codaddict