问题描述
我想将RGB/十六进制格式的颜色转换为最接近的网络安全颜色.
I want to convert a color either in RGB/Hex format to its nearest web-safe color.
有关网络安全色的详细信息可以在这里找到: http://en.wikipedia.org/wiki/Web_safe_color
Details about a websafe color can be found here: http://en.wikipedia.org/wiki/Web_safe_color
此网站( http://www.colortools.net/color_make_web-safe.html)可以按照我想要的方式进行操作,但是我不确定如何在Python中进行操作.有人可以帮我吗?
This website(http://www.colortools.net/color_make_web-safe.html) is able to do the way I want to, but I am not sure how to go about it in Python. Can anyone help me out here?
推荐答案
尽管网络安全用语有些用词不当,但对于颜色量化确实非常有用.它简单,快速,灵活且无处不在.它还允许使用RGB十六进制速记,例如#369
而不是#336699
.这是一个演练:
Despite being somewhat of a misnomer, the web safe color palette is indeed quite useful for color quantization. It's simple, fast, flexible, and ubiquitous. It also allows for RGB hex shorthand such as #369
instead of #336699
. Here's a walkthrough:
- 网络安全色是RGB三胞胎,每个值是以下六个值之一:
00, 33, 66, 99, CC, FF
.因此,我们可以将最大RGB值255
除以五(比可能的总值小一),以得到多个值51
. - 通过除以
255
标准化通道值(这使它成为0-1
而不是0-255
的值). - 乘以
5
,然后对结果取整以确保其精确. -
乘以
51
以获得最终的Web安全值.总之,这看起来像:
- Web safe colors are RGB triplets, with each value being one of the following six:
00, 33, 66, 99, CC, FF
. So we can divide the max RGB value255
by five (one less than the total possible values) to get a multiple value,51
. - Normalize the channel value by dividing by
255
(this makes it a value from0-1
instead of0-255
). - Multiply by
5
, and round the result to make sure it stays exact. Multiply by
51
to get the final web safe value. All together, this looks something like:
def getNearestWebSafeColor(r, g, b):
r = int(round( ( r / 255.0 ) * 5 ) * 51)
g = int(round( ( g / 255.0 ) * 5 ) * 51)
b = int(round( ( b / 255.0 ) * 5 ) * 51)
return (r, g, b)
print getNearestWebSafeColor(65, 135, 211)
像其他人建议的那样,无需疯狂地比较颜色或创建巨大的查找表. :-)
No need to go crazy comparing colors or creating huge lookup tables, as others have suggested. :-)
这篇关于将RGB颜色转换为调色板中最接近的颜色(网络安全色)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!