RGB 到十六进制和十六进制到 RGB
如何将 RGB 格式的颜色转换为十六进制格式,反之亦然?
例如,将 '#0080C0'
转换为 (0, 128, 192)
。
How to convert colors in RGB format to hex format and vice versa?
For example, convert '#0080C0'
to (0, 128, 192)
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
注意:
rgbToHex
的两个版本都期望r
、g
和b
为整数值,因此如果您有非整数值,则需要进行自己的舍入。以下将对 RGB 到十六进制转换进行操作并添加任何所需的零填充:
另一种方式转换:
最后,
rgbToHex()
的替代版本,如 @casablanca 的答案 中讨论并建议@cwolves 的评论:2012 年 12 月 3 日更新
这是
hexToRgb()
的一个版本,它还可以解析速记的十六进制三元组,例如“#03F”:Note: both versions of
rgbToHex
expect integer values forr
,g
andb
, so you'll need to do your own rounding if you have non-integer values.The following will do to the RGB to hex conversion and add any required zero padding:
Converting the other way:
Finally, an alternative version of
rgbToHex()
, as discussed in @casablanca's answer and suggested in the comments by @cwolves:Update 3 December 2012
Here's a version of
hexToRgb()
that also parses a shorthand hex triplet such as "#03F":hexToRgb 的替代版本:
编辑:2017 年 3 月 28 日
这是另一种方法
似乎更快编辑:8/11/2017
经过更多测试后,上面的新方法并不更快:(。尽管这是一种有趣的替代方法。
An alternative version of hexToRgb:
Edit: 3/28/2017
Here is another approach
that seems to be even fasterEdit: 8/11/2017
The new approach above after more testing is not faster :(. Though it is a fun alternate way.
Tim Down 的回答的 ECMAScript 6 版本
将 RGB 转换为十六进制
将十六进制转换为 RGB
返回数组
[r, g, b]
。也适用于速记十六进制三元组,例如"#03F"
。奖励:使用
padStart()
方法将 RGB 转换为十六进制请注意,此答案使用最新的 ECMAScript 功能,旧版浏览器不支持这些功能。如果您希望此代码在所有环境中工作,您应该使用 Babel 来编译您的代码。
ECMAScript 6 version of Tim Down's answer
Converting RGB to hex
Converting hex to RGB
Returns an array
[r, g, b]
. Works also with shorthand hex triplets such as"#03F"
.Bonus: RGB to hex using
padStart()
methodNote that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code.
这是我的版本:
Here's my version:
我假设您指的是 HTML 样式的十六进制表示法,即
#rrggbb
。您的代码几乎是正确的,只是您的顺序颠倒了。它应该是:另外,使用位移位可能会使它更容易阅读:
I'm assuming you mean HTML-style hexadecimal notation, i.e.
#rrggbb
. Your code is almost correct, except you've got the order reversed. It should be:Also, using bit-shifts might make it a bit easier to read:
尝试(rgba 此处;奖金在这里)
Try (rgba here; bonus here)
单行功能十六进制到 RGBA
支持短
#fff
和长#ffffff
形式。支持 Alpha 通道(不透明度)。
不关心是否指定了哈希值,在两种情况下都有效。
例子:
One-line functional HEX to RGBA
Supports both short
#fff
and long#ffffff
forms.Supports alpha channel (opacity).
Does not care if hash specified or not, works in both cases.
examples:
令人惊讶的是这个答案还没有出现。
Surprised this answer hasn't come up.
此代码接受 #fff 和 #ffffff 变体和不透明度。
This code accept #fff and #ffffff variants and opacity.
按位解决方案通常很奇怪。但在这种情况下,我想这更优雅
Bitwise solution normally is weird. But in this case I guess that is more elegant ????
Usage:
(2017) SIMPLE ES6 可组合箭头函数
我无法抗拒与那些可能使用 ES6 编写一些现代函数/组合 js 的人分享这个。以下是我在颜色模块中使用的一些漂亮的单行代码,该模块为数据可视化进行颜色插值。
请注意,这根本不处理 Alpha 通道。
顺便说一句,如果你喜欢这种风格/语法,我编写了一个全彩色模块(现代颜色),你可以从 npm 获取。我这样做是为了可以使用 prop getter 进行转换并解析几乎任何内容(Color.parse(anything))。如果你像我一样经常处理颜色,那么值得一看。
(2017) SIMPLE ES6 composable arrow functions
I can't resist sharing this for those who may be writing some modern functional/compositional js using ES6. Here are some slick one-liners I am using in a color module that does color interpolation for data visualization.
Note that this does not handle the alpha channel at all.
BTW, If you like this style/syntax, I wrote a full color module (modern-color) you can grab from npm. I made it so I could use prop getters for conversion and parse virtually anything (Color.parse(anything)). Worth a look if you deal with color a lot like I do.
这可用于从计算样式属性中获取颜色:
参考:https:/ /github.com/k-gun/so/blob/master/so_util.js
This could be used for getting colors from computed style propeties:
Ref: https://github.com/k-gun/so/blob/master/so_util.js
十六进制转RGB
RGB 到十六进制
另外,如果有人需要在线工具,我已经构建了十六进制到RGB,反之亦然。
Hex to RGB
RGB to Hex
Also if someone need online tool, I have built Hex to RGB and vice versa.
// 忽略 hsl 表示法,颜色值通常表示为名称、rgb、rgba 或十六进制-
// 十六进制可以是 3 个值或 6 个
值。 // Rgb 可以是百分比也可以是整数值。
// 最好至少考虑所有这些格式。
// Ignoring hsl notation, color values are commonly expressed as names, rgb, rgba or hex-
// Hex can be 3 values or 6.
// Rgb can be percentages as well as integer values.
// Best to account for all of these formats, at least.
你可以追求这样的东西吗?
显示#9687c8
May you be after something like this?
displays #9687c8
@蒂姆,添加到你的答案中(将其放入评论中有点尴尬)。
正如所写,我发现 rgbToHex 函数返回一个字符串,其中元素位于点之后,并且它要求 r、g、b 值落在 0-255 范围内。
我确信这对大多数人来说似乎是显而易见的,但我花了两个小时才弄清楚,到那时,原始方法已经膨胀到 7 行,然后我才意识到我的问题出在其他地方。因此,为了节省其他人的时间和利益,麻烦,这是我稍微修改过的代码,它检查先决条件并修剪掉字符串的无关位。
@ Tim, to add to your answer (its a little awkward fitting this into a comment).
As written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.
I'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.
如果您需要比较两个颜色值(以 RGB、名称颜色或十六进制值形式给出)或转换为十六进制,请使用 HTML5 画布对象。
If you need compare two color values (given as RGB, name color or hex value) or convert to HEX use HTML5 canvas object.
2021 版本
您可以简单地使用 rgb-hex & hex-rgb 因为它经过了实战测试具有其他解决方案中不可用的多种选项。
我最近正在构建一个颜色选择器和这2个包派上了用场。
用法
rgb-hex 十六
进制-rgb
2021 version
You can simply use rgb-hex & hex-rgb as it is battle-tested & has multiple options that are not available in other solutions.
I was recently building a Color Picker & these 2 packages came in handy.
Usage
rgb-hex
hex-rgb
接受字符串的简写版本:
检查它是否还不是十六进制
Shorthand version that accepts a string:
To check if it's not already hexadecimal
2022:如果您经常操作颜色并且不介意使用包,
请使用 tinycolor2。它是一个用于在 JavaScript 中进行颜色操作和转换的快速库(大约 400kb)。
它接受各种颜色字符串格式。例如:
RGB 到 HEX
十六进制到 RGB
访问文档以获取更多演示。
2022: If you often manipulate colors and doesn't mind using a package,
Use tinycolor2. It's a fast library (Around 400kb) for color manipulation and conversion in JavaScript.
It accepts various color string format. Like:
RGB to HEX
HEX to RGB
Visit documentation for more demo.
基本上,十六进制到 rgb:
如果你想要字符串
rgb 到十六进制:
basically, hex to rgb:
if you want string
rgb to hex:
我需要一个也接受无效值的函数,例如
rgb(-255, 255, 255)
rgb(510, 255, 255)
这是@cwolves 答案的衍生内容
i needed a function that accepts invalid values too like
rgb(-255, 255, 255)
rgb(510, 255, 255)
this is a spin off of @cwolves answer
使用这些函数可以毫无问题地获得结果。 :)
Use these Function to achive the result without any issue. :)
我建议使用经过良好测试和维护的库,而不是到处复制粘贴片段: Colors.js(适用于 Node.js 和浏览器)。它只有 7 KB(缩小后,压缩后更小)。
Instead of copy'n'pasting snippets found here and there, I'd recommend to use a well tested and maintained library: Colors.js (available for node.js and browser). It's just 7 KB (minified, gzipped even less).
我遇到了这个问题,因为我想解析任何颜色字符串值并能够指定不透明度,所以我编写了这个使用 画布 API。
关于
context.fillStyle
的注意事项:这是一个可用于测试输入的堆栈片段演示:
I came across this problem since I wanted to parse any color string value and be able to specify an opacity, so I wrote this function that uses the canvas API.
Note about
context.fillStyle
:Here's a Stack Snippet demo you can use to test inputs:
将 RGB 转换为十六进制的简单答案。这里颜色通道的值被限制在 0 到 255 之间。
A simple answer to convert RGB to hex. Here values of color channels are clamped between 0 and 255.
将 RGB 转换为十六进制
使用 padStart()
您可以使用
padStart()
使用此 oneliner:PS旧版浏览器不支持它,在此处检查其兼容性。
不使用padStart()
如果你不想使用
padStart()
,你可以实现这个函数:参数验证
如果您不确定谁将使用您的函数,则必须使用参数验证,以确保值有效(0 到 255 之间),为此,请在每个
return< 之前添加这些条件/代码>:
那么上面的两个例子就变成了:
十六进制到 RGB
为此,我们将使用一些 RegEx:
RGB to Hex
Using padStart()
You can use this oneliner using
padStart()
:P.S. it isn't supported on legacy browsers, check its compatibility here.
Without padStart()
If you don't want to use
padStart()
, you can implement this function instead:Parameters validation
If you're not sure who is going to use your function, you have to use the parameters validations, that the values are valid (between 0 and 255), to do so, add these conditions before each
return
:So the two above examples become:
Hex to RGB
For this, we are going to use some RegEx:
要直接从 jQuery 转换,您可以尝试:
For convert directly from jQuery you can try:
虽然这个答案不太可能完全适合这个问题,但它可能非常有用。
var toRgb = document.createElement('div');
toRg.style.color = "hsl(120, 60% , 70%)";
> toRgb.style.color;
< "rgb(133, 225, 133)"
您的颜色已转换为 Rgb适用于:Hsl、Hex
不适用于:命名颜色
While this answer is unlikely to fit the question perfectly it may be very useful none the less.
var toRgb = document.createElement('div');
toRg.style.color = "hsl(120, 60%, 70%)";
> toRgb.style.color;
< "rgb(133, 225, 133)"
Your color has been converted to RgbWorks for: Hsl, Hex
Does not work for: Named colors