I’m creating a fast lookup table for colors. Let’s say you give me shade of red, then I’ll convert it to closest web safe color and perform the lookup. It will return many different shades of red and it’s ok for my purposes.
The only problem I have right now is how do I convert a given RGB value to a web safe value? I’m using PIL and Python. I don’t mind writing my own algorithm either but it’s a bit too difficult for me.
I don’t know if there is a specific way to do it with PIL, but if you have an rgb colour and we define the closest web safe colour as the one where the distance in the rgb space is the smallest, you can do it as follows:
This is because web safe colors have 6 possible shades for each component: (0,51,102,153,204,255). If you a component in your colour is in the range [0,25] the closest is 0, if it’s in the range [26-76] the closest is 51, etc.
Alternatively, a shorter version for an rgb colour represented as a list:
EDIT: Edited to make sure it works even when Python uses non-integer numbers for colours and for Python 2 and 3.