【问题标题】:Converting a RGB color tuple to a six digit code将 RGB 颜色元组转换为六位代码
【发布时间】:2011-03-23 18:48:30
【问题描述】:

我需要将(0, 128, 64) 转换为类似"#008040" 的内容。我不知道如何称呼后者,这使得搜索变得困难。

【问题讨论】:

标签: python colors hex rgb


【解决方案1】:
''.join('%02x'%i for i in input)

可用于从 int 数进行十六进制转换

【讨论】:

    【解决方案2】:

    我真的很惊讶没有人建议这种方法:

    对于 Python 2 和 3:

    '#' + ''.join('{:02X}'.format(i) for i in colortuple)
    

    Python 3.6+:

    '#' + ''.join(f'{i:02X}' for i in colortuple)
    

    作为一个函数:

    def hextriplet(colortuple):
        return '#' + ''.join(f'{i:02X}' for i in colortuple)
    
    color = (0, 128, 64)
    print(hextriplet(color))
    
    #008040
    

    【讨论】:

      【解决方案3】:

      有一个名为 webcolors 的包。 https://github.com/ubernostrum/webcolors

      它有一个方法webcolors.rgb_to_hex

      >>> import webcolors
      >>> webcolors.rgb_to_hex((12,232,23))
      '#0ce817'
      

      【讨论】:

        【解决方案4】:

        您也可以使用相当高效的位操作符,尽管我怀疑您会担心这样的事情的效率。它也比较干净。请注意,它不会限制或检查边界。至少从 Python 2.7.17 开始就已支持此功能。

        hex(r << 16 | g << 8 | b)
        

        要改变它,让它以 # 开头,你可以这样做:

        "#" + hex(243 << 16 | 103 << 8 | 67)[2:]
        

        【讨论】:

          【解决方案5】:

          你可以使用 lambda 和 f-strings(在 python 3.6+ 中可用)

          rgb2hex = lambda r,g,b: f"#{r:02x}{g:02x}{b:02x}"
          hex2rgb = lambda hx: (int(hx[0:2],16),int(hx[2:4],16),int(hx[4:6],16))
          

          用法

          rgb2hex(r,g,b) #output = #hexcolor hex2rgb("#hex") #output = (r,g,b) hexcolor must be in #hex format

          【讨论】:

          • 不建议直接调用 lambda,原因有很多。我在一个经过审核的项目上使用它们,每个人都说同样的话,而不是直接调用。
          【解决方案6】:

          请注意,这只适用于 python3.6 及更高版本。

          def rgb2hex(color):
              """Converts a list or tuple of color to an RGB string
          
              Args:
                  color (list|tuple): the list or tuple of integers (e.g. (127, 127, 127))
          
              Returns:
                  str:  the rgb string
              """
              return f"#{''.join(f'{hex(c)[2:].upper():0>2}' for c in color)}"
          

          以上等价于:

          def rgb2hex(color):
              string = '#'
              for value in color:
                 hex_string = hex(value)  #  e.g. 0x7f
                 reduced_hex_string = hex_string[2:]  # e.g. 7f
                 capitalized_hex_string = reduced_hex_string.upper()  # e.g. 7F
                 string += capitalized_hex_string  # e.g. #7F7F7F
              return string
          

          【讨论】:

          • 这个函数 rgb2hex,应用于 (13,13,12),给出 0xDDC,但是网站 RGB to HEX 给出它为 0x0D0D0C,这也与数字应该是 13* 的想法一致65536+13*256+12,0xDDC被Python读取为3548。
          • CSS 颜色不一致。有 6 位十六进制颜色、3 位十六进制颜色、带小数和百分比的 rgb 表示法、hsl 等。我调整了公式以始终提供 6 位十六进制颜色,尽管我认为它可能更一致,我'不确定它是否更正确。
          【解决方案7】:

          这是一个更完整的函数,用于处理可能具有 [0,1] 范围或 [0,255] 范围内的 RGB 值的情况。 p>

          def RGBtoHex(vals, rgbtype=1):
            """Converts RGB values in a variety of formats to Hex values.
          
               @param  vals     An RGB/RGBA tuple
               @param  rgbtype  Valid valus are:
                                    1 - Inputs are in the range 0 to 1
                                  256 - Inputs are in the range 0 to 255
          
               @return A hex string in the form '#RRGGBB' or '#RRGGBBAA'
          """
          
            if len(vals)!=3 and len(vals)!=4:
              raise Exception("RGB or RGBA inputs to RGBtoHex must have three or four elements!")
            if rgbtype!=1 and rgbtype!=256:
              raise Exception("rgbtype must be 1 or 256!")
          
            #Convert from 0-1 RGB/RGBA to 0-255 RGB/RGBA
            if rgbtype==1:
              vals = [255*x for x in vals]
          
            #Ensure values are rounded integers, convert to hex, and concatenate
            return '#' + ''.join(['{:02X}'.format(int(round(x))) for x in vals])
          
          print(RGBtoHex((0.1,0.3,  1)))
          print(RGBtoHex((0.8,0.5,  0)))
          print(RGBtoHex((  3, 20,147), rgbtype=256))
          print(RGBtoHex((  3, 20,147,43), rgbtype=256))
          

          【讨论】:

          • 这太棒了!真正通用的功能。谢谢,理查德!
          【解决方案8】:

          我已经为它创建了一个完整的python程序,以下函数可以将rgb转换为hex,反之亦然。

          def rgb2hex(r,g,b):
              return "#{:02x}{:02x}{:02x}".format(r,g,b)
          
          def hex2rgb(hexcode):
              return tuple(map(ord,hexcode[1:].decode('hex')))
          

          您可以在以下链接查看完整的代码和教程:RGB to Hex and Hex to RGB conversion using Python

          【讨论】:

          • 它不适用于 rgb 的十进制值。你能建议我解决它吗?
          • 圆形。最终颜色应该不会有太大差异。
          【解决方案9】:
          def RGB(red,green,blue): return '#%02x%02x%02x' % (red,green,blue)
          
          background = RGB(0, 128, 64)
          

          我知道 Python 中的单行语句不一定会受到善待。但有时我无法抗拒利用 Python 解析器所允许的优势。这与 Dietrich Epp 的解决方案(最好的)相同,但包含在单行函数中。所以,谢谢迪特里希!

          我现在将它与 tkinter 一起使用 :-)

          【讨论】:

            【解决方案10】:

            Python 3.6 中,您可以使用 f-strings 来使其更简洁:

            rgb = (0,128, 64)
            f'#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}'
            

            当然你可以把它放到一个函数中,作为奖励,值会被四舍五入并转换为int

            def rgb2hex(r,g,b):
                return f'#{int(round(r)):02x}{int(round(g)):02x}{int(round(b)):02x}'
            
            rgb2hex(*rgb)
            

            【讨论】:

              【解决方案11】:

              这是一个老问题,但为了提供信息,我开发了一个包,其中包含一些与颜色和颜色图相关的实用程序,并包含您希望将三元组转换为十六进制值的 rgb2hex 函数(可以在许多其他包中找到,例如 matplotlib )。它在 pypi 上

              pip install colormap
              

              然后

              >>> from colormap import rgb2hex
              >>> rgb2hex(0, 128, 64)
              '##008040'
              

              检查输入的有效性(值必须介于 0 和 255 之间)。

              【讨论】:

              • 我尝试使用 rgb2hex 但收到错误“ImportError: No module named easydev.tools”。你能提出任何解决方案吗?
              • 尝试重新安装easydev。然后'pip3 install easydev'。
              【解决方案12】:
              def clamp(x): 
                return max(0, min(x, 255))
              
              "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
              

              这使用字符串格式化的首选方法,如described in PEP 3101。它还使用min()max 来确保0 &lt;= {r,g,b} &lt;= 255

              更新添加了如下建议的钳位功能。

              更新 从问题的标题和给定的上下文来看,应该很明显,这需要 [0,255] 中的 3 个整数,并且在传递 3 个这样的整数时总是会返回一个颜色。不过从cmets来看,这可能不是每个人都看得一清二楚,所以还是明确说明一下吧:

              提供三个int 值,这将返回一个表示颜色的有效十六进制三元组。如果这些值在 [0,255] 之间,那么它会将这些值视为 RGB 值并返回与这些值对应的颜色。

              【讨论】:

                【解决方案13】:
                triplet = (0, 128, 64)
                print '#'+''.join(map(chr, triplet)).encode('hex')
                

                from struct import pack
                print '#'+pack("BBB",*triplet).encode('hex')
                

                python3 略有不同

                from base64 import b16encode
                print(b'#'+b16encode(bytes(triplet)))
                

                【讨论】:

                  【解决方案14】:

                  使用格式运算符%:

                  >>> '#%02x%02x%02x' % (0, 128, 64)
                  '#008040'
                  

                  请注意,它不会检查边界...

                  >>> '#%02x%02x%02x' % (0, -1, 9999)
                  '#00-1270f'
                  

                  【讨论】:

                  • 两位数的限制真的有必要吗?只要 RGB 值在 0-255 的适当范围内,您就不需要它。所以你可以做'#%x%x%x' % (r, g, b)
                  • 实际上我现在看到,如果你的值为 0,则需要用另一个 0 填充它。因此 02 使其成为两位数。
                  最近更新 更多