Skip to content

Instantly share code, notes, and snippets.

@otykhonruk
Last active November 5, 2018 22:49
Show Gist options
  • Save otykhonruk/09e165702ef2c28ff514086d574b722a to your computer and use it in GitHub Desktop.
Save otykhonruk/09e165702ef2c28ff514086d574b722a to your computer and use it in GitHub Desktop.
from collections import namedtuple
from operator import itemgetter, sub
class rgb:
# https://www.w3.org/TR/REC-html40/types.html#h-6.5
_NAMED_COLORS = {
'black': 0x000000,
'green': 0x008000,
'silver': 0xC0C0C0,
'lime': 0x00FF00,
'gray': 0x808080,
'olive': 0x808000,
'white': 0xFFFFFF,
'yellow': 0xFFFF00,
'maroon': 0x800000,
'navy': 0x000080,
'red': 0xFF0000,
'blue': 0x0000FF,
'purple': 0x800080,
'teal': 0x008080,
'fuchsia': 0xFF00FF,
'aqua': 0x00FFFF,
}
def __init__(self, a, b=None, c=None):
if b is None and c is None:
self.__value = a
elif b is not None and c is not None:
self.__value = (a << 16) | (b << 8) | c
else:
raise ValueError()
def __getitem__(self, i):
return (self.__value >> (2 - i)*8) & 0xff
def __iter__(self):
return (self[i] for i in range(3))
def __repr__(self):
return 'rgb({}, {}, {})'.format(*self)
r, g, b = map(property, map(itemgetter, range(3)))
def sq_dist(self, other):
return sum(x*x for x in (a-b for a, b in zip(self, other)))
def dist(self, other):
return self.sq_dist(other) ** 0.5
@classmethod
def from_hexstring(cls, colorstr):
hexstr = colorstr[1:]
return cls(int(hexstr, 16))
@classmethod
def from_string(cls, colorstr):
"""
1. #RRGGBB (TODO: #RGB)
2. rgb(r, g, b)
3. color name
"""
if colorstr.startswith('#'):
return cls.from_hexstring(colorstr)
elif colorstr.startswith('rgb'):
return eval(colorstr)
elif colorstr in cls._NAMED_COLORS:
return cls(cls._NAMED_COLORS[colorstr])
else:
raise ValueError('Invalid color: ' + colorstr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment