color.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import re
  2. NAME_TO_HEX = {
  3. 'aqua': '#0ff',
  4. 'black': '#000',
  5. 'blue': '#00f',
  6. 'fuchsia': '#f0f',
  7. 'lime': '#0f0',
  8. 'white': '#fff',
  9. 'yellow': '#ff0'
  10. }
  11. HEX_TO_NAME = {
  12. '#808080': 'gray',
  13. '#008000': 'green',
  14. '#800000': 'maroon',
  15. '#000080': 'navy',
  16. '#8080000': 'olive',
  17. '#800080': 'purple',
  18. '#f00': 'red',
  19. '#c0c0c0': 'silver',
  20. '#008080': 'teal'
  21. }
  22. def _rgb_to_hex(rgb):
  23. return '#%02x%02x%02x' % rgb
  24. def color_shortcut(color):
  25. color = color.lower()
  26. # 'grey' and 'gray' are synonyms im most browsers, use 'gray' for correct
  27. # behaviour in IE
  28. if color == 'grey':
  29. color = 'gray'
  30. # Try converting RGB to hexadecimal, which is always shorter
  31. rgb = re.search(r'^rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)$', color)
  32. if rgb:
  33. color = _rgb_to_hex(map(int, rgb.groups()))
  34. # Check if hexadecimal code
  35. hexa = re.search(r'^#([a-z0-9]{6})$', color)
  36. if hexa:
  37. code = hexa.group(1)
  38. # Check if a 3-character variant is possible, e.g. 11ff00 -> 1f0
  39. if code[0] == code[1] and code[2] == code[3] and code[4] == code[5]:
  40. color = '#' + code[0] + code[2] + code[4]
  41. # Try to replace long hexadecimals with shorter color names
  42. if color in HEX_TO_NAME:
  43. return HEX_TO_NAME[color]
  44. elif color in NAME_TO_HEX:
  45. # Long color names can be replaced with shorted hexadecimal codes
  46. return NAME_TO_HEX[color]
  47. return color