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

后端 未结 10 1462
孤街浪徒
孤街浪徒 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'
    

提交回复
热议问题