0

Is there a convenient way to convert a floating-point value in the range [0,1] to a HTML hex color using a specified gradient?

At the moment, I am using:

.myclass {fill:red, fill-opacity:FLOATINGVAL}

But this is a somewhat restrictive gradient to work with.

Richard
  • 56,349
  • 34
  • 180
  • 251
  • Did you want it in Python or in CSS? – Ignacio Vazquez-Abrams Mar 06 '15 at 20:58
  • You can generate the color resulting from your CSS trick by blending the RGB values with white. See [this related](http://stackoverflow.com/questions/746899/how-to-calculate-an-rgb-colour-by-specifying-an-alpha-blending-amount). In the accepted answer `alpha` is your `FLOATINGVAL`, `new` is RGB for red (`[255,0,0]`) and `old` is RGB for white (`[255,255,255]`). – jedwards Mar 06 '15 at 21:02
  • I'm reminded of the Matplotlib gradients (see [here](http://matplotlib.org/examples/color/colormaps_reference.html)). I don't necessarily need to do everything in CSS: I just need to be able to specify a colour on some kind of gradient generated through some kind of package. – Richard Mar 06 '15 at 21:08

1 Answers1

2

Consider something like:

def blend(color, alpha, base=[255,255,255]):
    '''
    color should be a 3-element iterable,  elements in [0,255]
    alpha should be a float in [0,1]
    base should be a 3-element iterable, elements in [0,255] (defaults to white)
    '''
    out = [int(round((alpha * color[i]) + ((1 - alpha) * base[i]))) for i in range(3)]

    return out

print blend([255,0,0], 0)       # [255, 255, 255]   (White)
print blend([255,0,0], 0.25)    # [255, 191, 191]
print blend([255,0,0], 0.5)     # [255, 128, 128]
print blend([255,0,0], 0.75)    # [255, 64, 64]
print blend([255,0,0], 1)       # [255,0,0]         (Red)

# Or RGB hex values instead of lists:
def to_hex(color):
    return ''.join(["%02x" % e for e in color])

print to_hex(blend([255,0,0], 0))       # ffffff    (White)
print to_hex(blend([255,0,0], 0.25))    # ffbfbf
print to_hex(blend([255,0,0], 0.5))     # ff8080
print to_hex(blend([255,0,0], 0.75))    # ff4040
print to_hex(blend([255,0,0], 1))       # ff0000    (Red)

In terms of how this function works with the gradients you listed[1], color is the color at the right of the gradient bars while alpha is your position on the gradient bar (0.0 far left, 1.0 far right)

[1] This will only work with 2-color gradients -- your "color" and "white" (or whatever you specify base as) (i.e. gradients from that image like Blues, Greens, Grays, etc.)

You won't be able to generate gradients like YlGnBu with this function.

jedwards
  • 29,432
  • 3
  • 65
  • 92