How do I convert a hex triplet to an RGB tuple and back?

后端 未结 10 1453
孤街浪徒
孤街浪徒 2020-12-14 00:24

I\'d like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.

相关标签:
10条回答
  • 2020-12-14 01:06

    Here you go. I use it to convert color to graphviz color format in #RGBA format with prefix=#.

    def rgba_hex( color, prefix = '0x' ):
        if len( color ) == 3:
           color = color + (255,)
        hexColor = prefix + ''.join( [ '%02x' % x for x in color ] )
        return hexColor
    

    USAGE:

    In [3]: rgba_hex( (222, 100, 34) )
    Out[3]: '0xde6422ff'
    
    In [4]: rgba_hex( (0,255,255) )
    Out[4]: '0x00ffffff'
    
    In [5]: rgba_hex( (0,255,255,0) )
    Out[5]: '0x00ffff00'
    
    0 讨论(0)
  • 2020-12-14 01:07

    I found a simple way:

    red, green, blue = bytes.fromhex("aabbcc")
    
    0 讨论(0)
  • 2020-12-14 01:07

    with matplotlib

    matplotlib uses RGB tuples with values between 0 and 1:

    from matplotlib.colors import hex2color, rgb2hex
    
    hex_color = '#00ff00'
    rgb_color = hex2color(hex_color)
    hex_color_again = rgb2hex(rgb_color)
    

    both rgb_color and hex_color are in a format acceptable by matplotlib.

    with webcolors

    html uses RGB tuples with values between 0 and 255.

    you can convert between them with the module webcolors, using the functions hex_to_rgb, rgb_to_hex

    0 讨论(0)
  • 2020-12-14 01:09
    def hex_to_int_color(v):
        if v[0] == '#':
            v = v[1:]
        assert(len(v) == 6)
        return int(v[:2], 16), int(v[2:4], 16), int(v[4:6], 16)
    
    def int_to_hex_color(v):
        assert(len(v) == 3)
        return '#%02x%02x%02x' % v
    
    0 讨论(0)
提交回复
热议问题