

Calculate lighter/darker RGB colors in Python - coderdude
http://bitkickers.blogspot.com/2011/07/python-calculate-lighterdarker-rgb.html

======
gcr
Is that the right way of doing it though? Often it's more useful to make
colors a certain factor brighter or darker, not a certain offset brighter,
like this:

    
    
        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.

~~~
eurleif
I think HSL would probably be a better choice than HSV. Python has HSL support
built in, so you can do that pretty easily:

    
    
        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)

------
coderdude
I'm using this to calculate colors for a button pack I'm working on. This
guy's blog is really cool and it doesn't look like a lot of people know about
it yet. Every entry is a neat snippet. Mostly related to web development.

