如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
当前回答
2021年版
你可以简单地使用rgb-十六进制和十六进制-rgb,因为它是经过战斗测试的,有多个选项,在其他解决方案中是不可用的。
我最近正在构建一个颜色选择器&这2个包派上用场。
使用
rgb-hex
import rgbHex from 'rgb-hex';
rgbHex(65, 131, 196);
//=> '4183c4'
rgbHex('rgb(40, 42, 54)');
//=> '282a36'
rgbHex(65, 131, 196, 0.2);
//=> '4183c433'
rgbHex(40, 42, 54, '75%');
//=> '282a36bf'
rgbHex('rgba(40, 42, 54, 75%)');
//=> '282a36bf'
hex-rgb
import hexRgb from 'hex-rgb';
hexRgb('4183c4');
//=> {red: 65, green: 131, blue: 196, alpha: 1}
hexRgb('#4183c4');
//=> {red: 65, green: 131, blue: 196, alpha: 1}
hexRgb('#fff');
//=> {red: 255, green: 255, blue: 255, alpha: 1}
hexRgb('#22222299');
//=> {red: 34, green: 34, blue: 34, alpha: 0.6}
hexRgb('#0006');
//=> {red: 0, green: 0, blue: 0, alpha: 0.4}
hexRgb('#cd2222cc');
//=> {red: 205, green: 34, blue: 34, alpha: 0.8}
hexRgb('#cd2222cc', {format: 'array'});
//=> [205, 34, 34, 0.8]
hexRgb('#cd2222cc', {format: 'css'});
//=> 'rgb(205 34 34 / 80%)'
hexRgb('#000', {format: 'css'});
//=> 'rgb(0 0 0)'
hexRgb('#22222299', {alpha: 1});
//=> {red: 34, green: 34, blue: 34, alpha: 1}
hexRgb('#fff', {alpha: 0.5});
//=> {red: 255, green: 255, blue: 255, alpha: 0.5}
其他回答
CSS Level 4边注:一般来说,你想要能够将十六进制转换为RGB的原因是alpha通道,在这种情况下,你可以很快用CSS4添加一个十六进制。例如:#FF8800FF或#f80f表示全透明的橙色。
除此之外,下面的代码在一个函数中回答了这两个问题,从另一个函数到另一个函数。这接受一个可选的alpha通道,支持字符串数组格式,解析3,4,6,7个字符的十六进制,和rgb/a完整或部分字符串(百分比定义的rgb/a值除外)没有标志。
(如果支持IE,替换少量的ES6语法)
一句话:
function rgbaHex(c,a,i){return(Array.isArray(c)||(typeof c==='string'&&/,/.test(c)))?((c=(Array.isArray(c)?c:c.replace(/[\sa-z\(\);]+/gi,'').split(',')).map(s=>parseInt(s).toString(16).replace(/^([a-z\d])$/i,'0$1'))),'#'+c[0]+c[1]+c[2]):(c=c.replace(/#/,''),c=c.length%6?c.replace(/(.)(.)(.)/,'$1$1$2$2$3$3'):c,a=parseFloat(a)||null,`rgb${a?'a':''}(${[(i=parseInt(c,16))>>16&255,i>>8&255,i&255,a].join().replace(/,$/,'')})`);}
可读版本:
function rgbaHex(c, a) {
// RGBA to Hex
if (Array.isArray(c) || (typeof c === 'string' && /,/.test(c))) {
c = Array.isArray(c) ? c : c.replace(/[\sa-z\(\);]+/gi, '').split(',');
c = c.map(s => window.parseInt(s).toString(16).replace(/^([a-z\d])$/i, '0$1'));
return '#' + c[0] + c[1] + c[2];
}
// Hex to RGBA
else {
c = c.replace(/#/, '');
c = c.length % 6 ? c.replace(/(.)(.)(.)/, '$1$1$2$2$3$3') : c;
c = window.parseInt(c, 16);
a = window.parseFloat(a) || null;
const r = (c >> 16) & 255;
const g = (c >> 08) & 255;
const b = (c >> 00) & 255;
return `rgb${a ? 'a' : ''}(${[r, g, b, a].join().replace(/,$/,'')})`;
}
}
Usages:
rgbaHex(“# a8f”)
rgbaHex(“# aa88ff”)
rgbaHex(“# A8F”)
rgbaHex(“# AA88FF”)
rgbaHex('#AA88FF', 0.5)
rgbaHex(“# a8f”、“0.85”)
/ /等。
rgbaHex('rgba(170,136,255,0.8);')
rgbaHex('rgba(170,136,255,0.8)')
rgbaHex('rgb(170,136,255)')
rgbaHex('rg170,136,255')
rgbaHex(' 170,136,255 ')
rgbaHex 170,136,255,0.8 ([])
rgbaHex ([170136255])
/ /等。
接受字符串的简写版本:
function rgbToHex(a){ a=a.replace(/[^\d,]/g,“”).split(“,”); return“#”+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1) } document.write(rgbToHex(“rgb(255,255,255)”));
来检查它是否已经是十六进制
function rgbToHex(a){ if(~a.indexOf(“#”))返回 a; a=a.replace(/[^\d,]/g,“”).split(“,”); return“#”+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1) } document.write(“rgb: ”+rgbToHex(“rgb(255,255,255)”)+ “ -- hex: ”+rgbToHex(“#e2e2e2”));
看起来你在寻找这样的东西:
function hexstr(number) {
var chars = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
var low = number & 0xf;
var high = (number >> 4) & 0xf;
return "" + chars[high] + chars[low];
}
function rgb2hex(r, g, b) {
return "#" + hexstr(r) + hexstr(g) + hexstr(b);
}
我给洛达什做了这个。它将一个RGB字符串,如“30,209,19”转换为其对应的十六进制字符串“#1ed113”:
var rgb = '30,209,19';
var hex = _.reduce(rgb.split(','), function(hexAccumulator, rgbValue) {
var intColor = _.parseInt(rgbValue);
if (_.isNaN(intColor)) {
throw new Error('The value ' + rgbValue + ' was not able to be converted to int');
}
// Ensure a value such as 2 is converted to "02".
var hexColor = _.padLeft(intColor.toString(16), 2, '0');
return hexAccumulator + hexColor;
}, '#');
My example =) color: { toHex: function(num){ var str = num.toString(16); return (str.length<6?'#00'+str:'#'+str); }, toNum: function(hex){ return parseInt(hex.replace('#',''), 16); }, rgbToHex: function(color) { color = color.replace(/\s/g,""); var aRGB = color.match(/^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)$/i); if(aRGB) { color = ''; for (var i=1; i<=3; i++) color += Math.round((aRGB[i][aRGB[i].length-1]=="%"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)$/,'0$1'); } else color = color.replace(/^#?([\da-f])([\da-f])([\da-f])$/i, '$1$1$2$2$3$3'); return '#'+color; }