Skip to content

Instantly share code, notes, and snippets.

@StevenCHowell
Created July 13, 2017 20:23
Show Gist options
  • Save StevenCHowell/684fed4bcfd030967ae904fa1145a039 to your computer and use it in GitHub Desktop.
Save StevenCHowell/684fed4bcfd030967ae904fa1145a039 to your computer and use it in GitHub Desktop.
Scale a Hex color in Python
# Adapted from Thadeus Burgess' Python 2 code
# http://thadeusb.com/weblog/2010/10/10/python_scale_hex_color/
def clamp(val, minimum=0, maximum=255):
if val < minimum:
return minimum
if val > maximum:
return maximum
return val
def colorscale(hexstr, scalefactor):
"""
Scales a hex string by ``scalefactor``. Returns scaled hex string.
To darken the color, use a float value between 0 and 1.
To brighten the color, use a float value greater than 1.
>>> colorscale("#DF3C3C", .5)
#701E1E
>>> colorscale("#52D24F", 1.6)
#83FF7E
>>> colorscale("#4F75D2", 1)
#4F75D2
"""
hexstr = hexstr.strip('#')
if scalefactor < 0 or len(hexstr) != 6:
return hexstr
r, g, b = int(hexstr[:2], 16), int(hexstr[2:4], 16), int(hexstr[4:], 16)
r = clamp(int(round(r * scalefactor)))
g = clamp(int(round(g * scalefactor)))
b = clamp(int(round(b * scalefactor)))
return '#{}{}{}'.format(hex(r)[2:], hex(g)[2:], hex(b)[2:]).upper()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment