RGB到Hex和Hex到RGB
如何将RGB格式的颜色转换为十六进制格式,反之亦然?
例如,将'#0080C0'
转换为(0, 128, 192)
'#0080C0'
(0, 128, 192)
。
以下将做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
换一种方式:
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的评论中提出:
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
2012年12月3日更新
以下是hexToRgb()
的一个版本,它也解析了一个简写十六进制三元组,例如“#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";
另一个版本的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;
}
编辑: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];
}
编辑:8/11/2017更多的测试后,上述新的方法不是更快:(尽管它是一个有趣的替代方式。
这是我的版本:
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;
}
链接地址: http://www.djcxy.com/p/15391.html