RGB 到十六进制和十六进制到 RGB [英] RGB to hex and hex to RGB
问题描述
如何将RGB格式的颜色转换为十六进制格式,反之亦然?
How to convert colors in RGB format to hex format and vice versa?
例如将'#0080C0'
转换为(0, 128, 192)
.
推荐答案
注意:rgbToHex
的两个版本都期望 r
的整数值,g
和 b
,因此如果您有非整数值,则需要自己进行舍入.
Note: both versions 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.
以下将执行 RGB 到十六进制的转换并添加任何所需的零填充:
The following will do to the RGB to hex conversion and add any required zero padding:
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
换一种方式:
function hexToRgb(hex) {
var result = /^#?([a-fd]{2})([a-fd]{2})([a-fd]{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";
最后,rgbToHex()
的替代版本,如@casablanca 的回答中所述并在@cwolves 的评论中建议:
Finally, an alternative version of rgbToHex()
, as discussed in @casablanca's answer and suggested in the comments by @cwolves:
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
这是一个 hexToRgb()
版本,它也解析了一个速记的十六进制三元组,例如#03F":
Here's a version of hexToRgb()
that also parses a shorthand hex triplet such as "#03F":
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-fd])([a-fd])([a-fd])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-fd]{2})([a-fd]{2})([a-fd]{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";
这篇关于RGB 到十六进制和十六进制到 RGB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!