在 Python 中将十六进制转换为 RGB 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29643352/
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
Converting Hex to RGB value in Python
提问by Julian White
Working off Jeremy's response here: Converting hex color to RGB and vice-versaI was able to get a python program to convert preset colour hex codes (example #B4FBB8), however from an end-user perspective we can't ask people to edit code & run from there. How can one prompt the user to enter a hex value and then have it spit out a RGB value from there?
在这里工作过杰里米的回应:转换十六进制颜色为RGB,反之亦然从最终用户的角度,但是我能得到一个Python程序转换预设颜色的十六进制代码(例如#B4FBB8),我们不能要求人编辑代码并从那里运行。如何提示用户输入一个十六进制值,然后让它从那里吐出一个 RGB 值?
Here's the code I have thus far:
这是我迄今为止的代码:
def hex_to_rgb(value):
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def rgb_to_hex(rgb):
return '#%02x%02x%02x' % rgb
hex_to_rgb("#ffffff") # ==> (255, 255, 255)
hex_to_rgb("#ffffffffffff") # ==> (65535, 65535, 65535)
rgb_to_hex((255, 255, 255)) # ==> '#ffffff'
rgb_to_hex((65535, 65535, 65535)) # ==> '#ffffffffffff'
print('Please enter your colour hex')
hex == input("")
print('Calculating...')
print(hex_to_rgb(hex()))
Using the line print(hex_to_rgb('#B4FBB8'))
I'm able to get it to spit out the correct RGB value which is (180, 251, 184)
使用这条线,print(hex_to_rgb('#B4FBB8'))
我可以让它吐出正确的 RGB 值,即 (180, 251, 184)
It's probably super simple - I'm still pretty rough with Python.
这可能非常简单 - 我对 Python 仍然很粗糙。
采纳答案by John1024
I believe that this does what you are looking for:
我相信这可以满足您的要求:
h = input('Enter hex: ').lstrip('#')
print('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4)))
(The above was written for Python 3)
(以上是为 Python 3 编写的)
Sample run:
示例运行:
Enter hex: #B4FBB8
RGB = (180, 251, 184)
Writing to a file
写入文件
To write to a file with handle fhandle
while preserving the formatting:
要fhandle
在保留格式的同时写入带有句柄的文件:
fhandle.write('RGB = {}'.format( tuple(int(h[i:i+2], 16) for i in (0, 2, 4)) ))
回答by Matt Davidson
There are two small errors here!
这里有两个小错误!
hex == input("")
Should be:
应该:
user_hex = input("")
You want to assign the output of input()
to hex
, not check for comparison. Also, as mentioned in comments (@koukouviou) don't override hex
, instead call it something like user_hex
.
您想将输出分配input()
给hex
,而不是检查比较。此外,正如评论(@koukouviou)中所述,不要覆盖hex
,而是将其称为user_hex
.
Also:
还:
print(hex_to_rgb(hex()))
Should be:
应该:
print(hex_to_rgb(user_hex))
You want to use the value of hex, not the type's callable method (__call__
).
您想使用十六进制的值,而不是类型的可调用方法 ( __call__
)。
回答by vwrobel
回答by roberto
This function will return the RGBvalues in float from a Hexcode.
此函数将从十六进制代码以浮点数形式返回RGB值。
def hextofloats(h):
'''Takes a hex rgb string (e.g. #ffffff) and returns an RGB tuple (float, float, float).'''
return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#'
This function will return Hexcode from RGBvalue.
此函数将从RGB值返回十六进制代码。
def floatstohex(rgb):
'''Takes an RGB tuple or list and returns a hex RGB string.'''
return f'#{int(rgb[0]*255):02x}{int(rgb[1]*255):02x}{int(rgb[2]*255):02x}'
回答by terrygarcia
All the answers I've seen involve manipulation of a hex string. In my view, I'd prefer to work with encoded integers and RGB triples themselves, not just strings. This has the benefit of not requiring that a color be represented in hexadecimal-- it could be in octal, binary, decimal, what have you.
我见过的所有答案都涉及对十六进制字符串的操作。在我看来,我更喜欢使用编码的整数和 RGB 三元组本身,而不仅仅是字符串。这样做的好处是不需要用十六进制表示颜色——它可以是八进制、二进制、十进制,你有什么。
Converting an RGB triple to an integer is easy.
将 RGB 三元组转换为整数很容易。
rgb = (0xc4, 0xfb, 0xa1) # (196, 251, 161)
def rgb2int(r,g,b):
return (256**2)*r + 256*g + b
c = rgb2int(*rgb) # 12909473
print(hex(c)) # '0xc4fba1'
We need a little more math for the opposite direction. I've lifted the following from my answer to a similar Math exchange question.
对于相反的方向,我们需要更多的数学运算。我从我对类似数学交换问题的回答中提取了以下内容。
c = 0xc4fba1
def int2rgb(n):
b = n % 256
g = int( ((n-b)/256) % 256 ) # always an integer
r = int( ((n-b)/256**2) - g/256 ) # ditto
return (r,g,b)
print(tuple(map(hex, int2rgb(c)))) # ('0xc4', '0xfb', '0xa1')
With this approach, you can convert to and from strings with ease.
使用这种方法,您可以轻松地在字符串之间进行转换。
回答by Peter Mitrano
PIL also has this function, in ImageColor.
PIL也有这个功能,在ImageColor中。
from PIL import ImageColor
ImageColor.getrgb("#9b9b9b")
And if you want the numbers from 0 to 1
如果你想要从 0 到 1 的数字
[i/256 for i in ImageColor.getrgb("#9b9b9b")]
回答by SuperNova
You can use ImageColor
from Pillow.
您可以ImageColor
从枕头使用。
>>> from PIL import ImageColor
>>> ImageColor.getcolor("#23a9dd", "RGB")
(35, 169, 221)
回答by Saad
As HEXcodes can be like "#FFF"
, "#000"
, "#0F0"
or even "#ABC"
that only use three digits.These are just the shorthand version of writing a code, which are the three pairs of identical digits "#FFFFFF"
, "#000000"
, "#00FF00"
or "#AABBCC"
.
由于十六进制代码可以像"#FFF"
,"#000"
,"#0F0"
甚至"#ABC"
只使用三位数字。这些只是编写代码的速记版本,即三对相同的数字"#FFFFFF"
、"#000000"
、"#00FF00"
或"#AABBCC"
。
This function is made in such a way that it can work with both shorthands as well as the full length of HEX codes. Returns RGB values if the argument hsl = False
else return HSL values.
此函数的制作方式使其既可以使用速记,也可以使用全长的十六进制代码。如果参数hsl = False
else 返回 HSL 值,则返回 RGB值。
import re
def hex_to_rgb(hx, hsl=False):
"""Converts a HEX code into RGB or HSL.
Args:
hx (str): Takes both short as well as long HEX codes.
hsl (bool): Converts the given HEX code into HSL value if True.
Return:
Tuple of length 3 consisting of either int or float values."""
if re.compile(r'#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$').match(hx):
div = 255.0 if hsl else 0
if len(hx) <= 4:
return tuple(int(hx[i]*2, 16) / div if div else
int(hx[i]*2, 16) for i in (1, 2, 3))
else:
return tuple(int(hx[i:i+2], 16) / div if div else
int(hx[i:i+2], 16) for i in (1, 3, 5))
else:
raise ValueError(f'"{hx}" is not a valid HEX code.')
Here are some IDLE outputs.
下面是一些空闲输出。
hex_to_rgb('#FFB6C1')
>>> (255, 182, 193)
hex_to_rgb('#ABC')
>>> (170, 187, 204)
hex_to_rgb('#FFB6C1', hsl=True)
>>> (1.0, 0.7137254901960784, 0.7568627450980392)
hex_to_rgb('#ABC', hsl=True)
>>> (0.6666666666666666, 0.7333333333333333, 0.8)
hex_to_rgb('#00FFFF')
>>> (0, 255, 255)
hex_to_rgb('#0FF')
>>> (0, 255, 255)