Javascript RGB 转十六进制和十六进制转 RGB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5623838/
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
RGB to Hex and Hex to RGB
提问by Sindar
How to convert colors in RGB format to Hex format and vice versa?
如何将 RGB 格式的颜色转换为十六进制格式,反之亦然?
For example, convert '#0080C0'
to (0, 128, 192)
.
例如,转换'#0080C0'
为(0, 128, 192)
.
回答by Tim Down
Note: both version of rgbToHex
expect integer values for r
, g
and b
, so you'll need to do your own rounding if you have non-integer values.
注意:,和 的两个版本都rgbToHex
期望整数值,因此如果您有非整数值,则需要自己进行舍入。r
g
b
The following will do to the RGB to hex conversion and add any required zero padding:
以下将执行 RGB 到十六进制的转换并添加任何所需的零填充:
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
Converting the other way:
换一种方式:
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
alert(hexToRgb("#0033ff").g); // "51";
Finally, an alternative version of rgbToHex()
, as discussed in @casablanca's answerand suggested in the comments by @cwolves:
最后,还有一个替代版本rgbToHex()
,如@casablanca的回答中所述并在@cwolves 的评论中建议:
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
Update 3 December 2012
2012 年 12 月 3 日更新
Here's a version of hexToRgb()
that also parses a shorthand hex triplet such as "#03F":
这是一个hexToRgb()
也解析速记十六进制三元组的版本,例如“#03F”:
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
alert(hexToRgb("#0033ff").g); // "51";
alert(hexToRgb("#03f").g); // "51";
回答by David
An alternative version of hexToRgb:
hexToRgb 的替代版本:
function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
Edit: 3/28/2017
Here is another approach that seems to be even faster
编辑:3/28/2017 这是另一种方法 这似乎更快
function hexToRgbNew(hex) {
var arrBuff = new ArrayBuffer(4);
var vw = new DataView(arrBuff);
vw.setUint32(0,parseInt(hex, 16),false);
var arrByte = new Uint8Array(arrBuff);
return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}
Edit: 8/11/2017 The new approach above after more testing is not faster :(. Though it is a fun alternate way.
编辑:8/11/2017 经过更多测试后,上面的新方法并不快:(。虽然这是一种有趣的替代方法。
回答by Micha? Per?akowski
ECMAScript 6 version of Tim Down's answer
Tim Down 的回答的ECMAScript 6 版本
Converting RGB to hex
将 RGB 转换为十六进制
const rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => {
const hex = x.toString(16)
return hex.length === 1 ? '0' + hex : hex
}).join('')
console.log(rgbToHex(0, 51, 255)); // '#0033ff'
Converting hex to RGB
将十六进制转换为 RGB
Returns an array [r, g, b]
. Works also with shorthand hex triplets such as "#03F"
.
返回一个数组[r, g, b]
。也适用于速记十六进制三元组,例如"#03F"
.
const hexToRgb = hex =>
hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
,(m, r, g, b) => '#' + r + r + g + g + b + b)
.substring(1).match(/.{2}/g)
.map(x => parseInt(x, 16))
console.log(hexToRgb("#0033ff")) // [0, 51, 255]
console.log(hexToRgb("#03f")) // [0, 51, 255]
Bonus: RGB to hex using padStart()
method
奖励:RGB 到十六进制使用padStart()
方法
const rgbToHex = (r, g, b) => '#' + [r, g, b]
.map(x => x.toString(16).padStart(2, '0')).join('')
console.log(rgbToHex(0, 51, 255)); // '#0033ff'
Note 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 Babelto compile your code.
请注意,此答案使用了较旧的浏览器不支持的最新 ECMAScript 功能。如果你想让这段代码在所有环境中都能运行,你应该使用Babel来编译你的代码。
回答by FelipeC
Here's my version:
这是我的版本:
function rgb2hex(red, green, blue) {
var rgb = blue | (green << 8) | (red << 16);
return '#' + (0x1000000 + rgb).toString(16).slice(1)
}
function hex2rgb(hex) {
// long version
r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (r) {
return r.slice(1,4).map(function(x) { return parseInt(x, 16); });
}
// short version
r = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
if (r) {
return r.slice(1,4).map(function(x) { return 0x11 * parseInt(x, 16); });
}
return null;
}
回答by casablanca
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:
我假设您的意思是 HTML 样式的十六进制表示法,即#rrggbb
. 您的代码几乎是正确的,只是您的顺序颠倒了。它应该是:
var decColor = red * 65536 + green * 256 + blue;
Also, using bit-shifts might make it a bit easier to read:
此外,使用位移可能会使阅读更容易一些:
var decColor = (red << 16) + (green << 8) + blue;
回答by rezoner
function hex2rgb(hex) {
return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}
回答by falko
This code accept #fff and #ffffff variants and opacity.
此代码接受#fff 和#ffffff 变体和不透明度。
function hex2rgb(hex, opacity) {
var h=hex.replace('#', '');
h = h.match(new RegExp('(.{'+h.length/3+'})', 'g'));
for(var i=0; i<h.length; i++)
h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16);
if (typeof opacity != 'undefined') h.push(opacity);
return 'rgba('+h.join(',')+')';
}
回答by K-Gun
This could be used for getting colors from computed style propeties:
这可用于从计算样式属性中获取颜色:
function rgbToHex(color) {
color = ""+ color;
if (!color || color.indexOf("rgb") < 0) {
return;
}
if (color.charAt(0) == "#") {
return color;
}
var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color),
r = parseInt(nums[2], 10).toString(16),
g = parseInt(nums[3], 10).toString(16),
b = parseInt(nums[4], 10).toString(16);
return "#"+ (
(r.length == 1 ? "0"+ r : r) +
(g.length == 1 ? "0"+ g : g) +
(b.length == 1 ? "0"+ b : b)
);
}
// not computed
<div style="color: #4d93bc; border: 1px solid red;">...</div>
// computed
<div style="color: rgb(77, 147, 188); border: 1px solid rgb(255, 0, 0);">...</div>
console.log( rgbToHex(color) ) // #4d93bc
console.log( rgbToHex(borderTopColor) ) // #ff0000
回答by Denis
One-line functional HEX to RGBA
单行函数式 HEX 转 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.
支持短形式#fff
和长#ffffff
形式。
支持 alpha 通道(不透明度)。
不关心是否指定了哈希,在这两种情况下都有效。
function hexToRGBA(hex, opacity) {
return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(opacity||1).join(',') + ')';
}
examples:
例子:
hexToRGBA('#fff') -> rgba(255,255,255,1)
hexToRGBA('#ffffff') -> rgba(255,255,255,1)
hexToRGBA('#fff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('#ffffff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('fff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('ffffff', .2) -> rgba(255,255,255,0.2)
回答by Aral Roca
Bitwise solution normally is weird. But in this case I guess that is more elegant
按位解决方案通常很奇怪。但在这种情况下,我想这更优雅
function hexToRGB(hexColor){
return {
red: (hexColor >> 16) & 0xFF,
green: (hexColor >> 8) & 0xFF,
blue: hexColor & 0xFF,
}
}
Usage:
用法:
const {red, green, blue } = hexToRGB(0xFF00FF)
console.log(red) // 255
console.log(green) // 0
console.log(blue) // 255