在 Python 中生成随机十六进制颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13998901/
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
Generating a Random Hex Color in Python
提问by sinθ
For a Django App, each "member" is assigned a color to help identify them. Their color is stored in the database and then printed/copied into the HTML when it is needed. The only issue is that I am unsure how to generate random Hexcolors in python/django. It's easy enough to generate RGB colors, but to store them I would either need to a) make three extra columns in my "Member" model or b) store them all in the same column and use commas to separate them, then, later, parse the colors for the HTML. Neither of these are very appealing, so, again, I'm wondering how to generate random Hexcolors in python/django.
对于 Django 应用程序,每个“成员”都被分配了一种颜色来帮助识别它们。它们的颜色存储在数据库中,然后在需要时打印/复制到 HTML 中。唯一的问题是我不确定如何Hex在 python/django 中生成随机颜色。生成 RGB 颜色很容易,但要存储它们,我需要 a) 在我的“成员”模型中创建三个额外的列,或者 b) 将它们全部存储在同一列中并使用逗号将它们分开,然后,稍后,解析 HTML 的颜色。这些都不是很吸引人,所以,再次,我想知道如何Hex在 python/django 中生成随机颜色。
采纳答案by Dmitry Dubovitsky
import random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))
回答by Keith Randall
Just store them as an integer with the three channels at different bit offsets (just like they are often stored in memory):
只需将它们存储为具有不同位偏移的三个通道的整数(就像它们通常存储在内存中一样):
value = (red << 16) + (green << 8) + blue
(If each channel is 0-255). Store that integer in the database and do the reverse operation when you need to get back to the distinct channels.
(如果每个通道是 0-255)。将该整数存储在数据库中,并在需要返回不同通道时执行相反的操作。
回答by StoryTeller - Unslander Monica
For generating random anything, take a look at the random module
要生成随机的任何东西,请查看random 模块
I would suggest you use the module to generate a random integer, take it's modulo 2**24, and treat the top 8 bits as R, that middle 8 bits as G and the bottom 8 as B.
It can all be accomplished with div/mod or bitwise operations.
我建议您使用该模块生成一个随机整数,取其模数2**24,并将前 8 位视为 R,将中间 8 位视为 G,将后 8 位视为 B。
这一切都可以通过 div/mod 或按位完成操作。
回答by Roland Smith
Store it as a HTML color value:
将其存储为 HTML 颜色值:
Updated:now accepts both integer (0-255) and float (0.0-1.0) arguments. These will be clamped to their allowed range.
更新:现在接受整数 (0-255) 和浮点数 (0.0-1.0) 参数。这些将被限制在允许的范围内。
def htmlcolor(r, g, b):
def _chkarg(a):
if isinstance(a, int): # clamp to range 0--255
if a < 0:
a = 0
elif a > 255:
a = 255
elif isinstance(a, float): # clamp to range 0.0--1.0 and convert to integer 0--255
if a < 0.0:
a = 0
elif a > 1.0:
a = 255
else:
a = int(round(a*255))
else:
raise ValueError('Arguments must be integers or floats.')
return a
r = _chkarg(r)
g = _chkarg(g)
b = _chkarg(b)
return '#{:02x}{:02x}{:02x}'.format(r,g,b)
Result:
结果:
In [14]: htmlcolor(250,0,0)
Out[14]: '#fa0000'
In [15]: htmlcolor(127,14,54)
Out[15]: '#7f0e36'
In [16]: htmlcolor(0.1, 1.0, 0.9)
Out[16]: '#19ffe5'
回答by Fatih Serhat Gerdan
import random
def hex_code_colors():
a = hex(random.randrange(0,256))
b = hex(random.randrange(0,256))
c = hex(random.randrange(0,256))
a = a[2:]
b = b[2:]
c = c[2:]
if len(a)<2:
a = "0" + a
if len(b)<2:
b = "0" + b
if len(c)<2:
c = "0" + c
z = a + b + c
return "#" + z.upper()
回答by Eneko Alonso
Here is a simple way:
这是一个简单的方法:
import random
color = "%06x" % random.randint(0, 0xFFFFFF)
To generate a random 3 char color:
要生成随机 3 个字符的颜色:
import random
color = "%03x" % random.randint(0, 0xFFF)
%xin C-based languages is a string formatter to format integers as hexadecimal strings while 0xis the prefix to write numbers in base-16.
%x在基于 C 的语言中,是一个字符串格式化程序,用于将整数格式化为十六进制字符串,而0x是在 base-16 中写入数字的前缀。
Colors can be prefixed with "#" if needed (CSS style)
如果需要,颜色可以用“#”作为前缀(CSS 样式)
回答by AllTheTime1111
hex_digits = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
digit_array = []
for i in xrange(6):
digit_array.append(hex_digits[randint(0,15)])
joined_digits = ''.join(digit_array)
color = '#' + joined_digits
回答by Dinesh K.
little late to the party,
派对迟到了,
import random
chars = '0123456789ABCDEF'
['#'+''.join(sample(chars,6)) for i in range(N)]
回答by Sevalad
import random
def generate_color():
color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(3)))
return color
回答by mknecht
This has been done before. Rather than implementing this yourself, possibly introducing errors, you may want to use a ready library, for example Faker. Have a look at the color providers, in particular hex_digit.
这是以前做过的。与其自己实现(可能会引入错误),不如使用现成的库,例如Faker。看看颜色供应商,特别是hex_digit。
In [1]: from faker import Factory
In [2]: fake = Factory.create()
In [3]: fake.hex_color()
Out[3]: u'#3cae6a'
In [4]: fake.hex_color()
Out[4]: u'#5a9e28'

