4 points · by coderdude · 14y ago · 4 comments
def adjust_color_darken(r,g,b, factor):
return [
r*factor,
g*factor,
b*factor
]
def adjust_color_lighten(r,g,b, factor):
return [
255 - (255-r)*(1-factor),
255 - (255-g)*(1-factor),
255 - (255-b)*(1-factor)
]
The original snippet also doesn't work for colors whose values are less than 16. def hex_to_rgb(hex):
return [(hex_color[x:x+2],16) for x in [1, 3, 5]]
def rgb_to_hex(r,g,b):
return "#%02x%02x%02x" % (r,g,b)
A more "correct" solution might be to convert the RGB colors to HSV or some other color space, adjust the brightness, and convert back to RGB. from colorsys import rgb_to_hls, hls_to_rgb
def adjust_color_lightness(r, g, b, factor):
h, l, s = rgb_to_hls(r / 255.0, g / 255.0, b / 255.0)
l = max(min(l * factor, 1.0), 0.0)
r, g, b = hls_to_rgb(h, l, s)
return int(r * 255), int(g * 255), int(b * 255)
def lighten_color(r, g, b, factor=0.1):
return adjust_color_lightness(r, g, b, 1 + factor)
def darken_color(r, g, b, factor=0.1):
return adjust_color_lightness(r, g, b, 1 - factor)
Though, I'm not sure if doing it by multiplying is correct. I don't like that lighten_color(*darken_color(r, g, b)) != (r, g, b)