Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm: Create color from string

I want to create a color from a given string. The string does not have to be related to the resulting color in any form, but the same string should always result in the same color.

This question is not bound to a specific programming language, so the "Color" should be in a language-independent format like RGB.

It would be good if the algorithm creates colors in a wide colorspectrum and not just greyish colors.

Perfectly would be something like this (C++):

#include <string>

int getRedFromString( std::string givenString )
{ /*Your code here...*/ }

int getGreenFromString( std::string givenString )
{ /*Your code here...*/ }

int getBlueFromString( std::string givenString )
{ /*Your code here...*/ }

int main()
{
    std::string colorString = "FooBar";
    int R = getRedFromString  ( colorString );
    int G = getGreenFromString( colorString );
    int B = getBlueFromString ( colorString );
}
like image 323
MOnsDaR Avatar asked May 01 '11 13:05

MOnsDaR


3 Answers

Take a hash of the string, then use the first three bytes of the hash as Red, Blue, and Green values.

like image 96
SLaks Avatar answered Oct 18 '22 12:10

SLaks


You could use any hashing algorithm to create a value from the string that is always the same for any given string, and get the color components from that.

The GetHashCode method in .NET for example returns an integer, so it would be easy to create an RGB value from that:

int RGB = colorString.GetHashCode() & FFFFFFh;

or

int code = colorString.GetHashCode();
int B = code & FFh;
code >>= 8;
int G = code & FFh;
code >>= 8;
int R = code & FFh;
like image 32
Guffa Avatar answered Oct 18 '22 12:10

Guffa


I will have a try with an MD5 on the string:

from hashlib import md5

def get_color_tuple(item)
    hash = md5(item).hexdigest()
    hash_values = (hash[:8], hash[8:16], hash[16:24]) # note: we ignore the values from 24 to 32, but it shouldn't be a problem.
    return tuple(int(value, 16)%256 for value in hash_values)

What the algorithm does is basically this: it gets the first three chunks of 4 bytes (i.e. 8 characters) , and returns them in a tuple modulo 256, so that their range will be in [0, 255]

like image 25
Gabi Purcaru Avatar answered Oct 18 '22 12:10

Gabi Purcaru