在 Python 中将 RGB 颜色元组转换为六位代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3380726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:45:09  来源:igfitidea点击:

Converting a RGB color tuple to a six digit code, in Python

pythoncolorsrgb

提问by rectangletangle

I need to convert (0, 128, 64) to something like this #008040. I'm not sure what to call the latter, making searching difficult.

我需要将 (0, 128, 64) 转换为类似 #008040 的值。我不确定如何称呼后者,使搜索变得困难。

采纳答案by Dietrich Epp

Use the format operator %:

使用格式运算符%

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

Note that it won't check bounds...

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

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

回答by Jesse Dhillon

def clamp(x): 
  return max(0, min(x, 255))

"#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))

This uses the preferred method of string formatting, as described in PEP 3101. It also uses min()and maxto ensure that 0 <= {r,g,b} <= 255.

这使用了首选的字符串格式化方法,如PEP 3101 中所述。它还使用min()max确保0 <= {r,g,b} <= 255.

Updateadded the clamp function as suggested below.

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

UpdateFrom the title of the question and the context given, it should be obvious that this expects 3 ints in [0,255] and will always return a color when passed 3 such ints. However, from the comments, this may not be obvious to everyone, so let it be explicitly stated:

更新从问题的标题和给出的上下文来看,很明显,这需要 [0,255] 中的 3 个整数,并且在传递 3 个这样的整数时将始终返回颜色。但是,从评论来看,这可能不是每个人都能看出来的,那么就明确说明一下:

Provided three intvalues, this will return a valid hex triplet representing a color. If those values are between [0,255], then it will treat those as RGB values and return the color corresponding to those values.

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

回答by John La Rooy

triplet = (0, 128, 64)
print '#'+''.join(map(chr, triplet)).encode('hex')

or

或者

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

python3 is slightly different

python3略有不同

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

回答by Thomas Cokelaer

This is an old question but for information, I developed a package with some utilities related to colors and colormaps and contains the rgb2hex function you were looking to convert triplet into hexa value (which can be found in many other packages, e.g. matplotlib). It's on pypi

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

pip install colormap

and then

进而

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

Validity of the inputs is checked (values must be between 0 and 255).

检查输入的有效性(值必须在 0 到 255 之间)。

回答by Mohd Shibli

I have created a full python program for it the following functions can convert rgb to hex and vice versa.

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

def rgb2hex(r,g,b):
    return "#{:02x}{:02x}{:02x}".format(r,g,b)

def hex2rgb(hexcode):
    return tuple(map(ord,hexcode[1:].decode('hex')))

You can see the full code and tutorial at the following link : RGB to Hex and Hex to RGB conversion using Python

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

回答by toto_tico

In Python 3.6, you can use f-stringsto make this cleaner:

Python 3.6 中,您可以使用f-strings使其更清晰:

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


Of course you can put that into a function, and as a bonus, values get rounded and converted to int:

当然,您可以将其放入function 中,作为奖励,值会四舍五入并转换为 int

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

rgb2hex(*rgb)

回答by MikeyB

def RGB(red,green,blue): return '#%02x%02x%02x' % (red,green,blue)

background = RGB(0, 128, 64)

I know one-liners in Python aren't necessarily looked upon kindly. But there are times where I can't resist taking advantage of what the Python parser does allow. It's the same answer as Dietrich Epp's solution (the best), but wrapped up in a single line function. So, thank you Dietrich!

我知道 Python 中的单行代码不一定会被友好地看待。但有时我无法抗拒利用 Python 解析器允许的功能。它与 Dietrich Epp 的解决方案(最好的)相同,但包含在单行函数中。所以,谢谢迪特里希!

I'm using it now with tkinter :-)

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

回答by Richard

Here is a more complete function for handling situations in which you may have RGB values in the range [0,1]or the range [0,255].

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

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))

回答by Brian Bruggeman

Note that this only works with python3.6 and above.

请注意,这仅适用于 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)}"

The above is the equivalent of:

以上相当于:

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

回答by Kaneki

you can use lambda and f-strings(available in python 3.6+)

您可以使用 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))

usage

用法

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

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