1

Is there a simple way to change the lightness of a color given as RGB string?

E.g.

in_RGB = '#FF0000'  --> out_RGB = '#CC0000'
Don
  • 16,928
  • 12
  • 63
  • 101

1 Answers1

3

It's not that hard to convert a hex string to an RGB 3-tuple.

Once you've done that, you can use the colorsys module (or if you prefer to implement it yourself, the equations here) to convert from RGB to HSL, then do the manipulation you want, and then convert back from HSL to RGB.

Then just convert back to hex, add the # sign again, and you're good to go.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • Thanks. To make it simpler I actually did it by dividing each RGB component for the same ratio and then obtain the string back. – Don Mar 09 '11 at 09:04
  • 1
    I converted the string using 3 statements: `R = int(str_hex[0:2], 16); G = int(str_hex[2:4], 16); B = int(str_hex[4:6], 16);`. Is there a more straightforward way? – Don Mar 09 '11 at 09:06
  • `r,g,b = (int(str_hex[2x:2x+2]) for x in xrange(3))` is an option, albeit not much more straightforward. – Amber Mar 09 '11 at 16:33