colors.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. from colorsys import rgb_to_hsv, hsv_to_rgb
  2. def rgb_to_hex(r, g, b):
  3. r = unicode(hex(int(r * 255))[2:]).zfill(2)
  4. g = unicode(hex(int(g * 255))[2:]).zfill(2)
  5. b = unicode(hex(int(b * 255))[2:]).zfill(2)
  6. return r + g+ b
  7. def hex_to_rgb(color):
  8. if len(color) == 6:
  9. r, g, b = color[0:2], color[2:4], color[4:6]
  10. elif len(color) == 3:
  11. r, g, b = color[0], color[1], color[2]
  12. else:
  13. raise ValueError('"%s" is not correct HTML Hex Color.')
  14. r, g, b = float(int(r, 16)), float(int(g, 16)), float(int(b, 16))
  15. r /= 255.0
  16. g /= 255.0
  17. b /= 255.0
  18. return r, g, b
  19. def spin(color, rad):
  20. append_hex = False
  21. if color[0] == '#':
  22. append_hex = True
  23. color = color[1:]
  24. r, g, b = hex_to_rgb(color)
  25. h, s, v = rgb_to_hsv(r, g, b)
  26. if rad:
  27. h += float(rad) / 360
  28. r, g, b = hsv_to_rgb(h, s, v)
  29. if append_hex:
  30. return '#' + rgb_to_hex(r, g, b)
  31. return rgb_to_hex(r, g, b)
  32. def desaturate(color, steps, step, minimum=0):
  33. append_hex = False
  34. if color[0] == '#':
  35. append_hex = True
  36. color = color[1:]
  37. r, g, b = hex_to_rgb(color)
  38. h, s, v = rgb_to_hsv(r, g, b)
  39. minimum /= 100.0
  40. scope = s - minimum
  41. s = minimum + (scope / steps * (steps - step))
  42. r, g, b = hsv_to_rgb(h, s, v)
  43. if append_hex:
  44. return '#' + rgb_to_hex(r, g, b)
  45. return rgb_to_hex(r, g, b)
  46. def lighten(color, steps, step, maximum=100):
  47. append_hex = False
  48. if color[0] == '#':
  49. append_hex = True
  50. color = color[1:]
  51. r, g, b = hex_to_rgb(color)
  52. scope = maximum / 100.0 - min(r, g, b)
  53. step = scope / steps * step
  54. r += step
  55. g += step
  56. b += step
  57. r = 1 if r > 1 else r
  58. g = 1 if g > 1 else g
  59. b = 1 if b > 1 else b
  60. if append_hex:
  61. return '#' + rgb_to_hex(r, g, b)
  62. return rgb_to_hex(r, g, b)
  63. def darken(color, steps, step, minimum=0):
  64. append_hex = False
  65. if color[0] == '#':
  66. append_hex = True
  67. color = color[1:]
  68. r, g, b = hex_to_rgb(color)
  69. scope = minimum / 100.0 - max(r, g, b)
  70. step = scope / steps * step
  71. r += step
  72. g += step
  73. b += step
  74. r = 0 if r < 0 else r
  75. g = 0 if g < 0 else g
  76. b = 0 if b < 0 else b
  77. if append_hex:
  78. return '#' + rgb_to_hex(r, g, b)
  79. return rgb_to_hex(r, g, b)