如何将颜色在RGB格式转换为十六进制格式,反之亦然?

例如,将'#0080C0'转换为(0,128,192)。


我假设您指的是html风格的十六进制符号,即#rrggbb。你的代码几乎是正确的,只是顺序颠倒了。它应该是:

var decColor = red * 65536 + green * 256 + blue;

此外,使用位移位可能会让它更容易阅读:

var decColor = (red << 16) + (green << 8) + blue;

你想要这样的东西吗?

function RGB2HTML(red, green, blue)
{
    return '#' + red.toString(16) +
           green.toString(16) +
           blue.toString(16);
}

alert(RGB2HTML(150, 135, 200));

显示# 9687 c8


看起来你在寻找这样的东西:

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);
}

注意:rgbToHex的两个版本都期望r, g和b为整数值,所以如果你有非整数值,你需要自己做四舍五入。

下面将做RGB到十六进制的转换,并添加任何所需的零填充:

函数componentToHex(c) { var hex = c.toString(16); 返回十六进制。长度== 1 ?“0”+ hex: hex; } 函数rgbToHex(r, g, b) { 返回“#”+ componentToHex(r) + componentToHex(g) + componentToHex(b); } alert(rgbToHex(0, 51,255));/ / # 0033 ff

另一种转换方式:

函数hexToRgb(hex) { var结果= / ^ # ? (f \ d {2}) (f \ d {2}) (f \ d{2}) /美元i.exec(十六进制); 返回结果?{ r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) }: null; } 警报(hexToRgb (# 0033 ff) .g);/ /“51”;

最后,rgbToHex()的另一个版本,正如@casablanca的回答中所讨论的,并在@cwolves的评论中建议:

函数rgbToHex(r, g, b) { 返回“#”+ (1 < < 24 | r < < 16 g | < < 8 | b) .toString (16) .slice (1); } alert(rgbToHex(0, 51,255));/ / # 0033 ff

2012年12月3日更新

下面是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";


//忽略hsl符号,颜色值通常表示为名称,rgb, rgba或十六进制

//十六进制可以是3或6。

// Rgb可以是百分比也可以是整数值。

//至少最好能解释所有这些格式。

String.prototype.padZero= function(len, c){
    var s= this, c= c || "0", len= len || 2;
    while(s.length < len) s= c + s;
    return s;
}
var colors={
    colornames:{
        aqua: '#00ffff', black: '#000000', blue: '#0000ff', fuchsia: '#ff00ff',
        gray: '#808080', green: '#008000', lime: '#00ff00', maroon: '#800000',
        navy: '#000080', olive: '#808000', purple: '#800080', red: '#ff0000',
        silver: '#c0c0c0', teal: '#008080', white: '#ffffff', yellow: '#ffff00'
    },
    toRgb: function(c){
        c= '0x'+colors.toHex(c).substring(1);
        c= [(c>> 16)&255, (c>> 8)&255, c&255];
        return 'rgb('+c.join(',')+')';
    },
    toHex: function(c){
        var tem, i= 0, c= c? c.toString().toLowerCase(): '';
        if(/^#[a-f0-9]{3,6}$/.test(c)){
            if(c.length< 7){
                var A= c.split('');
                c= A[0]+A[1]+A[1]+A[2]+A[2]+A[3]+A[3];
            }
            return c;
        }
        if(/^[a-z]+$/.test(c)){
            return colors.colornames[c] || '';
        }
        c= c.match(/\d+(\.\d+)?%?/g) || [];
        if(c.length<3) return '';
        c= c.slice(0, 3);
        while(i< 3){
            tem= c[i];
            if(tem.indexOf('%')!= -1){
                tem= Math.round(parseFloat(tem)*2.55);
            }
            else tem= parseInt(tem);
            if(tem< 0 || tem> 255) c.length= 0;
            else c[i++]= tem.toString(16).padZero(2);
        }
        if(c.length== 3) return '#'+c.join('').toLowerCase();
        return '';
    }
}
//var c='#dc149c';
//var c='rgb(100%,25%,0)';
//
var c= 'red';
alert(colors.toRgb(c)+'\n'+colors.toHex(c));

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 经过更多测试后,上面的新方法并没有更快:(。虽然这是一种有趣的替代方式。


这段代码接受#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(',')+')';
}

如果你需要比较两个颜色值(给定为RGB,名称颜色或十六进制值)或转换为hex使用HTML5 canvas对象。

var canvas = document.createElement("canvas");
var ctx = this.canvas.getContext('2d');

ctx.fillStyle = "rgb(pass,some,value)";
var temp =  ctx.fillStyle;
ctx.fillStyle = "someColor";

alert(ctx.fillStyle == temp);

@ Tim,补充一下你的答案(把这个放进评论里有点尴尬)。

正如所写的,我发现rgbToHex函数返回一个包含元素的字符串,它要求r, g, b值落在0-255的范围内。

我相信这对大多数人来说是显而易见的,但我花了两个小时才弄明白,到那时,原来的方法已经膨胀到7行,直到我意识到我的问题在其他地方。因此,为了节省其他人的时间和麻烦,下面是我稍微修改过的代码,它检查了先决条件,并删除了字符串中无关的部分。

function rgbToHex(r, g, b) {
    if(r < 0 || r > 255) alert("r is out of bounds; "+r);
    if(g < 0 || g > 255) alert("g is out of bounds; "+g);
    if(b < 0 || b > 255) alert("b is out of bounds; "+b);
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
}

function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}

这可以用于从计算样式属性中获取颜色:

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

裁判:https://github.com/k-gun/so/blob/master/so_util.js


这个代码片段将十六进制转换为rgb, rgb转换为十六进制。

视图演示

function hexToRgb(str) { 
    if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(str) ) { 
        var hex = str.substr(1);
        hex = hex.length == 3 ? hex.replace(/(.)/g, '$1$1') : hex;
        var rgb = parseInt(hex, 16);               
        return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';
    } 

    return false; 
}

function rgbToHex(red, green, blue) {
    var out = '#';

    for (var i = 0; i < 3; ++i) {
        var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);

        if (isNaN(n) || n < 0 || n > 255) {
            return false;
        }

        out += (n < 16 ? '0' : '') + n.toString(16);
    }
    return out
}

我遇到了这个问题,因为我想要解析任何颜色字符串值,并能够指定不透明度,所以我写了这个使用canvas API的函数。

var toRGBA = function () {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  canvas.width = 1;
  canvas.height = 1;

  return function (color) {
    context.fillStyle = color;
    context.fillRect(0, 0, 1, 1);

    var data = context.getImageData(0, 0, 1, 1).data;

    return {
      r: data[0],
      g: data[1],
      b: data[2],
      a: data[3]
    };
  };
}();

关于context.fillStyle注意:

如果解析值导致失败,则必须忽略该值,属性必须保留其先前的值。

下面是一个你可以用来测试输入的Stack Snippet演示:

var toRGBA = function () { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.width = 1; canvas.height = 1; return function (color) { context.fillStyle = color; context.fillRect(0, 0, 1, 1); var data = context.getImageData(0, 0, 1, 1).data; return { r: data[0], g: data[1], b: data[2], a: data[3] }; }; }(); var inputs = document.getElementsByTagName('input'); function setColor() { inputs[1].value = JSON.stringify(toRGBA(inputs[0].value)); document.body.style.backgroundColor = inputs[0].value; } inputs[0].addEventListener('input', setColor); setColor(); input { width: 200px; margin: 0.5rem; } <input value="cyan" /> <input readonly="readonly" />


我需要一个函数,接受无效值太像

Rgb (- 255,255,255) Rgb (510, 255, 255)

这是@cwolves answer的衍生

function rgb(r, g, b) {
  this.c = this.c || function (n) {
    return Math.max(Math.min(n, 255), 0)
  };

  return ((1 << 24) + (this.c(r) << 16) + (this.c(g) << 8) + this.c(b)).toString(16).slice(1).toUpperCase();
}

以下是我的看法:

function rgbToHex(red, green, blue) {
  const rgb = (red << 16) | (green << 8) | (blue << 0);
  return '#' + (0x1000000 + rgb).toString(16).slice(1);
}

function hexToRgb(hex) {
  const normal = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
  if (normal) return normal.slice(1).map(e => parseInt(e, 16));

  const shorthand = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
  if (shorthand) return shorthand.slice(1).map(e => 0x11 * parseInt(e, 16));

  return null;
}

上面的一个干净的咖啡脚本版本(谢谢@TimDown):

rgbToHex = (rgb) ->
    a = rgb.match /\d+/g
    rgb  unless a.length is 3
    "##{ ((1 << 24) + (parseInt(a[0]) << 16) + (parseInt(a[1]) << 8) + parseInt(a[2])).toString(16).slice(1) }"

R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");

function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

使用这些函数来实现没有任何问题的结果。:)


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; }


我正在使用XAML数据,具有十六进制格式的#AARRGGBB (Alpha,红色,绿色,蓝色)。利用上面的答案,以下是我的解决方案:

function hexToRgba(hex) {
    var bigint, r, g, b, a;
    //Remove # character
    var re = /^#?/;
    var aRgb = hex.replace(re, '');
    bigint = parseInt(aRgb, 16);

    //If in #FFF format
    if (aRgb.length == 3) {
        r = (bigint >> 4) & 255;
        g = (bigint >> 2) & 255;
        b = bigint & 255;
        return "rgba(" + r + "," + g + "," + b + ",1)";
    }

    //If in #RRGGBB format
    if (aRgb.length >= 6) {
        r = (bigint >> 16) & 255;
        g = (bigint >> 8) & 255;
        b = bigint & 255;
        var rgb = r + "," + g + "," + b;

        //If in #AARRBBGG format
        if (aRgb.length == 8) {
            a = ((bigint >> 24) & 255) / 255;
            return "rgba(" + rgb + "," + a.toFixed(1) + ")";
        }
    }
    return "rgba(" + rgb + ",1)";
}

http://jsfiddle.net/kvLyscs3/


对于直接从jQuery转换,您可以尝试:

  function rgbToHex(color) {
    var bg = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
      return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return     "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
  }

  rgbToHex($('.col-tab-bar .col-tab span').css('color'))

function getRGB(color){
  if(color.length == 7){
    var r = parseInt(color.substr(1,2),16);
    var g = parseInt(color.substr(3,2),16);
    var b = parseInt(color.substr(5,2),16);    
    return 'rgb('+r+','+g+','+b+')' ;
  }    
  else
    console.log('Enter correct value');
}
var a = getRGB('#f0f0f0');
if(!a){
 a = 'Enter correct value'; 
}

a;

接受字符串的简写版本:

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”));


结合使用匿名函数和数组。地图为清洁工;更流线型的外观。

var write=function(str){document.body.innerHTML=JSON.stringify(str,null,' ');}; function hexToRgb(hex, asObj) { return (function(res) { return res == null ? null : (function(parts) { return !asObj ? parts : { r : parts[0], g : parts[1], b : parts[2] } }(res.slice(1,4).map(function(val) { return parseInt(val, 16); }))); }(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex))); } function rgbToHex(r, g, b) { return (function(values) { return '#' + values.map(function(intVal) { return (function(hexVal) { return hexVal.length == 1 ? "0" + hexVal : hexVal; }(intVal.toString(16))); }).join(''); }(arguments.length === 1 ? Array.isArray(r) ? r : [r.r, r.g, r.b] : [r, g, b])) } // Prints: { r: 255, g: 127, b: 92 } write(hexToRgb(rgbToHex(hexToRgb(rgbToHex(255, 127, 92), true)), true)); body{font-family:monospace;white-space:pre}


如果这有助于任何人,我的API有这些转换的函数。

<script src="http://api.xlww.net/xQuery/xQuery.js"></script>
<script>
  x.init();
  var rgb=new x.rgb(37,255,83);
  alert(rgb.hex);
  var hex=new x.hex("#ffa500");
  alert("("+hex.rgb[0]+","+hex.rgb[1]+","+hex.rgb[2]+")");
</script>

Tim Down给出的最高评级的答案提供了我所能看到的转换为RGB的最佳解决方案。我更喜欢这个十六进制转换的解决方案,因为它为转换到十六进制提供了最简洁的边界检查和零填充。

function RGBtoHex (red, green, blue) {
  red = Math.max(0, Math.min(~~red, 255));
  green = Math.max(0, Math.min(~~green, 255));
  blue = Math.max(0, Math.min(~~blue, 255));

  return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);
};

左移'<<'和或'|'操作符的使用也使这成为一个有趣的解决方案。


我给洛达什做了这个。它将一个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;
}, '#');

我发现了这个… http://jsfiddle.net/Mottie/xcqpF/1/light/

function rgb2hex(rgb){
    rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
    return (rgb && rgb.length === 4) ? "#" +
        ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
        ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
        ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

下面是将HEX颜色值分别更改为红色,绿色,蓝色的Javascript代码。

R = hexToR("#FFFFFF");
G = hexToG("#FFFFFF");
B = hexToB("#FFFFFF");

function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

我的hex2rbg版本:

接受短十六进制,如#fff 算法容量为o(n),应该比使用正则表达式快。如字符串。替换字符串。分裂,字符串。匹配等。 使用固定空间。 支持rgb和rgba。

如果你使用的是IE8,你可能需要删除hex.trim()。

如。

hex2rgb('#fff') //rgb(255,255,255) 
hex2rgb('#fff', 1) //rgba(255,255,255,1) 
hex2rgb('#ffffff') //rgb(255,255,255)  
hex2rgb('#ffffff', 1) //rgba(255,255,255,1)

代码:

function hex2rgb (hex, opacity) {
    hex = hex.trim();
    hex = hex[0] === '#' ? hex.substr(1) : hex;
    var bigint = parseInt(hex, 16), h = [];
    if (hex.length === 3) {
        h.push((bigint >> 4) & 255);
        h.push((bigint >> 2) & 255);
    } else {
        h.push((bigint >> 16) & 255);
        h.push((bigint >> 8) & 255);
    }
    h.push(bigint & 255);
    if (arguments.length === 2) {
        h.push(opacity);
        return 'rgba('+h.join()+')';
    } else {
        return 'rgb('+h.join()+')';
    }
}

一行功能HEX到RGBA

支持短#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(isFinite(opacity) ? opacity : 1).join(',') + ')';
}

例子:

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)

hexToRGBA('#ffffff', 0)  ->  rgba(255,255,255,0)
hexToRGBA('#ffffff', .5) ->  rgba(255,255,255,0.5)
hexToRGBA('#ffffff', 1)  ->  rgba(255,255,255,1)

我发现了这个,因为我认为它非常直截了当,有验证测试和支持alpha值(可选),这将适合这种情况。

只要注释掉regex行,如果你知道你在做什么,它会快一点。

function hexToRGBA(hex, alpha){
    hex = (""+hex).trim().replace(/#/g,""); //trim and remove any leading # if there (supports number values as well)
    if (!/^(?:[0-9a-fA-F]{3}){1,2}$/.test(hex)) throw ("not a valid hex string"); //Regex Validator
    if (hex.length==3){hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]} //support short form
    var b_int = parseInt(hex, 16);
    return "rgba("+[
        (b_int >> 16) & 255, //R
        (b_int >> 8) & 255, //G
        b_int & 255, //B
        alpha || 1  //add alpha if is set
    ].join(",")+")";
}

ECMAScript 6版本的Tim Down的答案

将RGB转换为十六进制

const rgbToHex = (r, g, b) => '#' + [r, g, b]。映射(x => { const十六进制= x.toString(16) 返回十六进制。长度=== 1 ?'0' + hex: hex }) . join () console.log(rgbToHex(0,51,255));/ / # 0033 ff的

将十六进制转换为RGB

返回一个数组[r, g, b]。工作也与速记十六进制三胞胎,如“#03F”。

const hexToRgb = hex => hex.replace (/ ^ # ? (\ d] [a - f) (\ d] [a - f) (\ d] [a - f) $ /我 ,(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]

附加: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));/ / # 0033 ff的

注意,这个答案使用了最新的ECMAScript特性,旧的浏览器不支持这些特性。如果希望此代码在所有环境中都能工作,则应该使用Babel来编译代码。


您可以尝试下面这段简单的代码。

用于十六进制到RGB

list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;

这将返回123,222,132

用于RGB到HEX

$rgb = (123,222,132),
$rgbarr = explode(",",$rgb,3);
echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]);

这将返回#7bde84


虽然这个答案不太可能完全符合问题,但它可能非常有用。

创建任意随机元素

var toRgb = document.createElement('div');

将任何有效的样式设置为要转换的颜色

toRg.style.颜色=“hsl(120、60%、70%)”;

再次调用style属性

> toRgb.style.color;

< "rgb(133,225,133)"您的颜色已转换为Rgb

适用于:Hsl,海克斯

不适用于:命名颜色


(2017) SIMPLE ES6组合箭头函数

我忍不住要把这个分享给那些可能正在使用ES6编写一些现代函数/复合js的人。下面是我在一个颜色模块中使用的一些光滑的单行程序,它为数据可视化做颜色插值。

注意,这根本不处理alpha通道。

const arrayToRGBString = rgb => `rgb(${rgb.join(',')})`;
const hexToRGBArray = hex => hex.match(/[A-Za-z0-9]{2}/g).map(v => parseInt(v, 16));
const rgbArrayToHex = rgb => `#${rgb.map(v => v.toString(16).padStart(2, '0')).join('')}`;
const rgbStringToArray = rgb => rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).splice(1, 3)
  .map(v => Number(v));
const rgbStringToHex = rgb => rgbArrayToHex(rgbStringToArray(rgb));

顺便说一句,如果你喜欢这种风格/语法,我写了一个全彩色模块(modern-color),你可以从npm中获取。我这样做,所以我可以使用道具getter转换和解析几乎任何东西(Color.parse(anything))。如果你和我一样对颜色很敏感的话,值得一看。


我建议使用一个经过良好测试和维护的库:Colors.js(可用于node.js和浏览器),而不是复制和粘贴到处都能找到的代码片段。它只有7 KB(压缩后更少)。


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])

/ /等。


基于@ michazperzhaakowski的回答(EcmaScipt 6)和他基于Tim Down的回答的回答

我写了一个转换hexToRGB函数的修改版本,增加了安全检查r/g/b颜色组件是否在0-255之间,而且函数可以接受数字r/g/b参数或字符串r/g/b参数,如下所示:

 function rgbToHex(r, g, b) {
     r = Math.abs(r);
     g = Math.abs(g);
     b = Math.abs(b);

     if ( r < 0 ) r = 0;
     if ( g < 0 ) g = 0;
     if ( b < 0 ) b = 0;

     if ( r > 255 ) r = 255;
     if ( g > 255 ) g = 255;
     if ( b > 255 ) b = 255;

    return '#' + [r, g, b].map(x => {
      const hex = x.toString(16);
      return hex.length === 1 ? '0' + hex : hex
    }).join('');
  }

为了安全地使用这个函数——你应该检查传递的字符串是否是真正的rbg字符串颜色——例如,一个非常简单的检查可以是:

if( rgbStr.substring(0,3) === 'rgb' ) {

  let rgbColors = JSON.parse(rgbStr.replace('rgb(', '[').replace(')', ']'))
  rgbStr = this.rgbToHex(rgbColors[0], rgbColors[1], rgbColors[2]);

  .....
}

一个完全不同的方法转换十六进制颜色代码到RGB没有正则表达式

它根据字符串长度处理#FFF和#FFFFFF格式。它从字符串的开头删除#,并将字符串的每个字符分割并将其转换为base10,并将其添加到其位置的相应索引中。

//Algorithm of hex to rgb conversion in ES5 function hex2rgbSimple(str){ str = str.replace('#', ''); return str.split('').reduce(function(result, char, index, array){ var j = parseInt(index * 3/array.length); var number = parseInt(char, 16); result[j] = (array.length == 3? number : result[j]) * 16 + number; return result; },[0,0,0]); } //Same code in ES6 hex2rgb = str => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]); //hex to RGBA conversion hex2rgba = (str, a) => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0,a||1]); //hex to standard RGB conversion hex2rgbStandard = str => `RGB(${str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]).join(',')})`; console.log(hex2rgb('#aebece')); console.log(hex2rgbSimple('#aebece')); console.log(hex2rgb('#aabbcc')); console.log(hex2rgb('#abc')); console.log(hex2rgba('#abc', 0.7)); console.log(hex2rgbStandard('#abc'));


当你在3D环境中工作时(webGL, ThreeJS),你有时需要为网格的不同面创建3个值,基本的一个(主色),一个浅一点的和一个深一点的:

material.color.set( 0x660000, 0xff0000, 0xff6666 ); // red cube

我们可以从主RBG颜色创建这3个值:255,0,0

function rgbToHex(rgb) { 
  var hex = Number(rgb).toString(16);
  if (hex.length < 2) {
       hex = "0" + hex;
  }
  return hex;
};

function convertToHex(r,g,b) { 

    var fact = 100;  // contrast 
    var code = '0x';

    // main color
    var r_hexa = rgbToHex(r);
    var g_hexa = rgbToHex(g);
    var b_hexa = rgbToHex(b);

    // lighter
    var r_light = rgbToHex(Math.floor(r+((1-(r/255))*fact)));
    var g_light = rgbToHex(Math.floor(g+((1-(g/255))*fact)));
    var b_light = rgbToHex(Math.floor(b+((1-(b/255))*fact)));

    // darker
    var r_dark = rgbToHex(Math.floor(r-((r/255)*(fact*1.5)))); // increase contrast
    var g_dark = rgbToHex(Math.floor(g-((g/255)*(fact*1.5))));
    var b_dark = rgbToHex(Math.floor(b-((b/255)*(fact*1.5))));

    var hexa = code+r_hexa+g_hexa+b_hexa;
    var light = code+r_light+g_light+b_light;
    var dark = code+r_dark+g_dark+b_dark;

    console.log('HEXs -> '+dark+" + "+hexa+" + "+light)

    var colors = [dark, hexa, light]; 
    return colors;

}

在你的ThreeJS代码中简单地写:

var material = new THREE.MeshLambertMaterial();
var c = convertToHex(255,0,0); // red cube needed
material.color.set( Number(c[0]), Number(c[1]), Number(c[2]) );

结果:

//                                 dark      normal     light
convertToHex(255,255,255) HEXs -> 0x696969 + 0xffffff + 0xffffff
convertToHex(255,0,0) HEXs -> 0x690000 + 0xff0000 + 0xff6464
convertToHex(255,127,0) HEXs -> 0x690000 + 0xff0000 + 0xff6464
convertToHex(100,100,100) HEXs -> 0x292929 + 0x646464 + 0xa0a0a0
convertToHex(10,10,10) HEXs -> 0x040404 + 0x0a0a0a + 0x6a6a6a


我为RGB和十六进制颜色做了一个小的Javascript颜色类,这个类还包括RGB和十六进制验证函数。我将代码作为一个片段添加到这个答案中。

var colorClass = function() { this.validateRgb = function(color) { return typeof color === 'object' && color.length === 3 && Math.min.apply(null, color) >= 0 && Math.max.apply(null, color) <= 255; }; this.validateHex = function(color) { return color.match(/^\#?(([0-9a-f]{3}){1,2})$/i); }; this.hexToRgb = function(color) { var hex = color.replace(/^\#/, ''); var length = hex.length; return [ parseInt(length === 6 ? hex['0'] + hex['1'] : hex['0'] + hex['0'], 16), parseInt(length === 6 ? hex['2'] + hex['3'] : hex['1'] + hex['1'], 16), parseInt(length === 6 ? hex['4'] + hex['5'] : hex['2'] + hex['2'], 16) ]; }; this.rgbToHex = function(color) { return '#' + ('0' + parseInt(color['0'], 10).toString(16)).slice(-2) + ('0' + parseInt(color['1'], 10).toString(16)).slice(-2) + ('0' + parseInt(color['2'], 10).toString(16)).slice(-2); }; }; var colors = new colorClass(); console.log(colors.hexToRgb('#FFFFFF'));// [255, 255, 255] console.log(colors.rgbToHex([255, 255, 255]));// #FFFFFF


不可变和人类可理解的版本,没有任何位魔法:

循环数组 使用Math.min()和Math.max()对值< 0或值> 255进行归一化 使用String.toString()将数字转换为十六进制符号 将前导零和修饰值附加到两个字符 将映射值连接到字符串

function rgbToHex(r, g, b) {
  return [r, g, b]
    .map(color => {
      const normalizedColor = Math.max(0, Math.min(255, color));
      const hexColor = normalizedColor.toString(16);

      return `0${hexColor}`.slice(-2);
    })
    .join("");
}

是的,它不会像位操作符那样性能好,但更可读和不可变,所以它不会修改任何输入


相当简单的一行。用逗号分隔rgb,忽略非数字,转换为十六进制,填充0,并以hashbang结束。

Var yellow = 'rgb(255,255,0)'; Var rgb2hex = STR => "#"+ STR .split(',')。map(s => (s.replace(/\D/g, ")|0). tostring(16))。Map (s => s.length < 2 ?"0"+s: s).join("); console.log (rgb2hex(黄色));


试(奖金)

let hex2rgb= c=> `rgb(${c.match(/\w\w/g).map(x=>+`0x${x}`)})`
let rgb2hex=c=>'#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``

让hex2rgb = c = > ' rgb ($ {c.match (w / \ \ w / g) . map (x = > + 0 x $ {x})})”; 让rgb2hex = c = > ' # ' + c.match (\ d + / g) . map (x = > (+ x) .toString (16) .padStart (2,0)) . join '; / /测试 console.log('#0080C0—>',hex2rgb('#0080C0')); console.log(“rgb(0, 128, 192)——>”,rgb2hex(的rgb (0, 128, 192)));


一个简单的答案,将RGB转换为十六进制。这里颜色通道的值被限定在0到255之间。

function RGBToHex(r = 0, g = 0, b = 0) {
    // clamp and convert to hex
    let hr = Math.max(0, Math.min(255, Math.round(r))).toString(16);
    let hg = Math.max(0, Math.min(255, Math.round(g))).toString(16);
    let hb = Math.max(0, Math.min(255, Math.round(b))).toString(16);
    return "#" +
        (hr.length<2?"0":"") + hr +
        (hg.length<2?"0":"") + hg +
        (hb.length<2?"0":"") + hb;
}

短箭头函数

对于那些重视短箭头功能的人。

Hex2rgb

大卫的答案的箭头函数版本

const hex2rgb = h => [(x=parseInt(h,16)) >> 16 & 255,x >> 8 & 255, x & 255];

一个更灵活的解决方案,支持短十六进制或哈希#

const hex2rgb = h => {
    if(h[0] == '#') {h = h.slice(1)};
    if(h.length <= 3) {h = h[0]+h[0]+h[1]+h[1]+h[2]+h[2]};
    h = parseInt(h,16);
    return [h >> 16 & 255,h >> 8 & 255, h & 255];
};

Rgb2hex

const rgb2hex = (r,g,b) => ((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);

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}

HTML converer :)

<!DOCTYPE html>
<html>
<body>

<p id="res"></p>

<script>
function hexToRgb(hex) {
  var res = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return "(" + parseInt(res[1], 16) + "," + parseInt(res[2], 16) + "," + parseInt(res[3], 16) + ")";
};

document.getElementById("res").innerHTML = hexToRgb('#0080C0');
</script>

</body>
</html>

建立了我自己的十六进制RGB转换器。我希望这能帮助到一些人。

我用react来做沙盒。

用法:

根据官方文档安装React,或者如果你全局安装了npx,运行npx create-react-app hexto -rgb

import React, { Component, Fragment } from 'react';
const styles = {
  display: 'block',
  margin: '20px auto',
  input: {
    width: 170,
  },
  button: {
    margin: '0 auto'
  }
}

//  test case 1
//    #f0f
//  test case 2
//    #ff00ff

class HexToRGBColorConverter extends Component {

  state = {
    result: false,
    color: "#ff00ff",
  }
  
  hexToRgb = color => {    
    let container = [[], [], []];
    // check for shorthand hax string
    if (color.length >= 3) {
      // remove hash from string
      // convert string to array
      color = color.substring(1).split("");
      for (let key = 0; key < color.length; key++) {        
        let value = color[key];
        container[2].push(value);
        // if the length is 3 we 
        // we need to add the value 
        // to the index we just updated
        if (color.length === 3) container[2][key] += value;
      }
      
      for (let index = 0; index < color.length; index++) {
        let isEven = index % 2 === 0;
        // If index is odd an number 
        // push the value into the first
        // index in our container
        if (isEven) container[0].push(color[index]);
        // If index is even an number 
        if (!isEven) {
          // again, push the value into the
          // first index in the container
          container[0] += color[index];
          // Push the containers first index
          // into the second index of the container
          container[1].push(container[0]);
          // Flush the first index of
          // of the container 
          // before starting a new set
          container[0] = [];
        }
      }
      // Check container length
      if (container.length === 3) {
        // Remove only one element of the array
        // Starting at the array's first index
        container.splice(0, 1);
        let values = container[color.length % 2];
        return {
          r: parseInt(values[0], 16),
          g: parseInt(values[1], 16),
          b: parseInt(values[2], 16)
        }
      }
    }
    return false;
  }  

  handleOnClick = event => {
    event.preventDefault();
    const { color } = this.state;
    const state = Object.assign({}, this.state);
    state.result = this.hexToRgb(color);
    this.setState(state);
  }

  handleOnChange = event => {
    event.preventDefault();
    const { value } = event.currentTarget;
    const pattern = /^([a-zA-Z0-9])/;
    const boundaries = [3, 6];
    if (
      pattern.test(value) &&
      boundaries.includes(value.length)
    ) {
      const state = Object.assign({}, this.state);
      state.color = `#${value}`;
      this.setState(state);
    }
  }

  render() {
    const { color, result } = this.state;
    console.log('this.state ', color, result);

    return (
      <Fragment>
        <input 
          type="text" 
          onChange={this.handleOnChange} 
          style={{ ...styles, ...styles.input }} />
        <button 
          onClick={this.handleOnClick}
          style={{ ...styles, ...styles.button }}>
          Convert hex to rgba
        </button>
        { 
          !!result && 
          <div style={{ textAlign: 'center' }}>
            Converted { color } to { JSON.stringify(result) }
          </div> 
        }
      </Fragment>
    )
  }
}
export default App;

快乐编码=)


十六进制到RGB

Const hex2rgb = (hex) => { const r = parseInt(十六进制。切片(1,3),16) const g = parseInt(十六进制。切片(3,5),16) const b = parseInt(十六进制。切片(5,7),16) //返回{r, g, b} //返回一个对象 返回[r, g, b] } console.log (hex2rgb (" # 0080 c0 "))

RGB转十六进制

rgb2hex = (r, g, b) => { Var RGB = (r << 16) | (g << 8) | b //返回'#' + rgb.toString(16) // #80c0 //返回'#' + (0x1000000 + rgb).toString(16).slice(1) // #0080c0 //或使用[padStart](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) 返回'#' + rgb.toString(16)。padStart (0) } Console.log (rgb2hex(0, 128, 192))

此外,如果有人需要在线工具,我已经建立了海克斯到RGB,反之亦然。


从HEX转换为RGB,其中RGB是0到1范围内的浮点值:

#FFAA22→{r: 0.5, g: 0, b:1}

我改编了@Tim Down的回答:


function convertRange(value,oldMin,oldMax,newMin,newMax) {
  return (Math.round(((((value - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin) * 10000)/10000)
}

function hexToRgbFloat(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: convertRange(parseInt(result[1],16), 0, 255, 0, 1),
    g: convertRange(parseInt(result[2],16), 0, 255, 0, 1),
    b: convertRange(parseInt(result[3],16), 0, 255, 0, 1)
  } : null;
}

console.log(hexToRgbFloat("#FFAA22")) // {r: 1, g: 0.6667, b: 0.1333}

我意识到这个问题有很多答案,但如果你像我一样,你知道你的HEX总是6个字符,带或不带#前缀,那么如果你想做一些快速内联的东西,这可能是最简单的方法。它不关心是否以散列开始。

var hex = "#ffffff";
var rgb = [
    parseInt(hex.substr(-6,2),16),
    parseInt(hex.substr(-4,2),16),
    parseInt(hex.substr(-2),16)
];

2022年:如果你经常操纵颜色,不介意使用包装,

使用tinycolor2。这是一个快速的JavaScript颜色操作和转换库(大约400kb)。

它接受各种颜色字符串格式。如:

tinycolor("#000"); // Hex3
tinycolor("#f0f0f6"); // Hex6
tinycolor("#f0f0f688"); // Hex8
tinycolor("f0f0f6"); // Hex withouth the number sign '#'
tinycolor("rgb (255, 0, 0)"); // RGB
tinycolor("rgba (255, 0, 0, .5)"); // RGBA
tinycolor({ r: 255, g: 0, b: 0 }); // RGB object
tinycolor("hsl(0, 100%, 50%)"); // HSL
tinycolor("hsla(0, 100%, 50%, .5)"); // HSLA
tinycolor("red"); // Named

RGB转十六进制

var color = tinycolor('rgb(0, 128, 192)');
color.toHexString(); //#0080C0

十六进制转RGB

var color = tinycolor('#0080C0');
color.toRgbString(); // rgb(0, 128, 192)

访问文档获取更多演示。


HEX转RGB (ES6) +测试[2022]

convertHexToRgb.ts:

/**
 * RGB color regexp
 */
export const RGB_REG_EXP = /rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/;

/**
 * HEX color regexp
 */
export const HEX_REG_EXP = /^#?(([\da-f]){3}|([\da-f]){6})$/i;

/**
 * Converts HEX to RGB.
 *
 * Color must be only HEX string and must be:
 *  - 7-characters starts with "#" symbol ('#ffffff')
 *  - or 6-characters without "#" symbol ('ffffff')
 *  - or 4-characters starts with "#" symbol ('#fff')
 *  - or 3-characters without "#" symbol ('fff')
 *
 * @function { color: string => string } convertHexToRgb
 * @return { string } returns RGB color string or empty string
 */
export const convertHexToRgb = (color: string): string => {
    const errMessage = `
    Something went wrong while working with colors...
    
    Make sure the colors provided to the "PieDonutChart" meet the following requirements:
    
    Color must be only HEX string and must be 
    7-characters starts with "#" symbol ('#ffffff')
    or 6-characters without "#" symbol ('ffffff')
    or 4-characters starts with "#" symbol ('#fff')
    or 3-characters without "#" symbol ('fff')
    
    - - - - - - - - -
    
    Error in: "convertHexToRgb" function
    Received value: ${color}
  `;

    if (
        !color
        || typeof color !== 'string'
        || color.length < 3
        || color.length > 7
    ) {
        console.error(errMessage);
        return '';
    }

    const replacer = (...args: string[]) => {
        const [
            _,
            r,
            g,
            b,
        ] = args;

        return '' + r + r + g + g + b + b;
    };

    const rgbHexArr = color
        ?.replace(HEX_REG_EXP, replacer)
        .match(/.{2}/g)
        ?.map(x => parseInt(x, 16));

    /**
     * "HEX_REG_EXP.test" is here to create more strong tests
     */
    if (rgbHexArr && Array.isArray(rgbHexArr) && HEX_REG_EXP.test(color)) {
        return `rgb(${rgbHexArr[0]}, ${rgbHexArr[1]}, ${rgbHexArr[2]})`;
    }

    console.error(errMessage);
    return '';
};

我正在使用Jest进行测试

color.spec.ts

describe('function "convertHexToRgb"', () => {
    it('returns a valid RGB with the provided 3-digit HEX color: [color = \'fff\']', () => {
        expect.assertions(2);

        const { consoleErrorMocked }  = mockConsole();
        const rgb = convertHexToRgb('fff');

        expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
        expect(consoleErrorMocked).not.toHaveBeenCalled();
    });

    it('returns a valid RGB with the provided 3-digit HEX color with hash symbol: [color = \'#fff\']', () => {
        expect.assertions(2);

        const { consoleErrorMocked }  = mockConsole();
        const rgb = convertHexToRgb('#fff');

        expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
        expect(consoleErrorMocked).not.toHaveBeenCalled();
    });

    it('returns a valid RGB with the provided 6-digit HEX color: [color = \'ffffff\']', () => {
        expect.assertions(2);

        const { consoleErrorMocked }  = mockConsole();
        const rgb = convertHexToRgb('ffffff');

        expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
        expect(consoleErrorMocked).not.toHaveBeenCalled();
    });

    it('returns a valid RGB with the provided 6-digit HEX color with the hash symbol: [color = \'#ffffff\']', () => {
        expect.assertions(2);

        const { consoleErrorMocked }  = mockConsole();
        const rgb = convertHexToRgb(TEST_COLOR);

        expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
        expect(consoleErrorMocked).not.toHaveBeenCalled();
    });

    it('returns an empty string when the provided value is not a string: [color = 1234]', () => {
        expect.assertions(2);

        const { consoleErrorMocked }  = mockConsole();

        // @ts-ignore
        const rgb = convertHexToRgb(1234);

        expect(rgb).toBe('');
        expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
    });

    it('returns an empty string when the provided color is too short: [color = \'FF\']', () => {
        expect.assertions(2);

        const { consoleErrorMocked }  = mockConsole();

        const rgb = convertHexToRgb('FF');

        expect(rgb).toBe('');
        expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
    });

    it('returns an empty string when the provided color is too long: [color = \'#fffffff\']', () => {
        expect.assertions(2);

        const { consoleErrorMocked }  = mockConsole();

        const rgb = convertHexToRgb('#fffffff');

        expect(rgb).toBe('');
        expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
    });

    it('returns an empty string when the provided value is looks like HEX color string but has invalid symbols: [color = \'#fffffp\']', () => {
        expect.assertions(2);

        const { consoleErrorMocked }  = mockConsole();
        const rgb = convertHexToRgb('#fffffp');

        expect(rgb).toBe('');
        expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
    });

    it('returns an empty string when the provided value is invalid: [color = \'*\']', () => {
        expect.assertions(2);

        const { consoleErrorMocked }  = mockConsole();

        const rgb = convertHexToRgb('*');

        expect(rgb).toBe('');
        expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
    });

    it('returns an empty string when the provided value is undefined: [color = undefined]', () => {
        expect.assertions(2);

        const { consoleErrorMocked }  = mockConsole();

        // @ts-ignore
        const rgb = convertHexToRgb(undefined);

        expect(rgb).toBe('');
        expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
    });
});

测试结果:

function "convertHexToRgb"
    √ returns a valid RGB with the provided 3-digit HEX color: [color = 'fff']
    √ returns a valid RGB with the provided 3-digit HEX color with hash symbol: [color = '#fff']
    √ returns a valid RGB with the provided 6-digit HEX color: [color = 'ffffff']
    √ returns a valid RGB with the provided 6-digit HEX color with the hash symbol: [color = '#ffffff']
    √ returns an empty string when the provided value is not a string: [color = 1234]
    √ returns an empty string when the provided color is too short: [color = 'FF']
    √ returns an empty string when the provided color is too long: [color = '#fffffff']
    √ returns an empty string when the provided value is looks like HEX color string but has invalid symbols: [color = '#fffffp']
    √ returns an empty string when the provided value is invalid: [color = '*']
    √ returns an empty string when the provided value is undefined: [color = undefined]

和mockConsole:

export const mockConsole = () => {
  const consoleError = jest.spyOn(console, 'error').mockImplementationOnce(() => undefined);
  return { consoleError };
};

RGB转十六进制

使用padStart ()

你可以使用padStart()来使用这个在线程序:

RGB = (r, g, b) => { 返回' #${[r, g, b].map((x) => x. tostring(16)。padStart(“0”)). join (" ")} '; }

另外,它在传统浏览器上不受支持,请在这里检查它的兼容性。

没有padStart ()

如果你不想使用padStart(),你可以实现这个函数:

RGB = (r, g, b) => { 返回' #${[r, g, b] . map ((n) = > n.toString(16)。长度=== 1 ?“0”+ n.toString(16): n.toString(16) ) . join (" ")} '; };

参数验证

如果你不确定谁将使用你的函数,你必须使用参数验证,即值是有效的(0到255之间),要做到这一点,在每次返回之前添加这些条件:

If (r > 255) r = 255;if (r < 0) r = 0; If (g > 255) g = 255;if (g < 0) g = 0; If (b > 255) b = 255;如果(b < 0) b = 0;

所以上面两个例子就变成了:

const rgb = (r, g, b) => { if (r > 255) r = 255; else if (r < 0) r = 0; if (g > 255) g = 255; else if (g < 0) g = 0; if (b > 255) b = 255; else if (b < 0) b = 0; return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`; }; const rgb2 = (r, g, b) => { if (r > 255) r = 255; else if (r < 0) r = 0; if (g > 255) g = 255; else if (g < 0) g = 0; if (b > 255) b = 255; else if (b < 0) b = 0; return `#${[r, g, b] .map((n) => n.toString(16).length === 1 ? "0" + n.toString(16) : n.toString(16) ) .join("")}`; };


十六进制到RGB

为此,我们将使用一些RegEx:

Const hex = (h) => { 返回h .replace ( / ^ # ? (\ d] [a - f) (\ d] [a - f) (\ d] [a - f) /我美元, (_, r, g, b) => "#" + r + r + g + g + b + b ) .substring (1) .match (/ {2} / g)。 .map((x) => parseInt(x, 16)); };


rgb字符串到十六进制字符串的可读联机程序:

rgb = "rgb(0,128,255)"
hex = '#' + rgb.slice(4,-1).split(',').map(x => (+x).toString(16).padStart(2,0)).join('')

返回这里“#0080ff”。


很惊讶这个答案没有出现。

不使用任何库#使用平台✔️ 3行,并处理任何颜色的浏览器支持。


const toRGB = (color) => {
    const { style } = new Option();
    style.color = color;
    return style.color;
}
// handles any color the browser supports and converts it.
console.log(toRGB("#333")) // rgb(51, 51, 51);
console.log(toRGB("hsl(30, 30%, 30%)")) 

哇。这些答案都不能处理分数的边缘情况,等等。当r, g, b为零时,位移版本也不起作用。

这是一个可以处理r g b是小数的版本。它对颜色之间的插值很有用,所以我也包括了这段代码。但它仍然不能处理r, g, b在0-255范围之外的情况

/**
 * Operates with colors.
 * @class Q.Colors
 */
 Q.Color = {
    /**
     * Get a color somewhere between startColor and endColor
     * @method toHex
     * @static
     * @param {String|Number} startColor 
     * @param {String|Number} endColor 
     * @param {String|Number} fraction 
     * @returns {String} a color as a hex string without '#' in front
     */
    toHex: function (r, g, b) {
        return [r, g, b].map(x => {
            const hex = Math.round(x).toString(16)
            return hex.length === 1 ? '0' + hex : hex
          }).join('');
    },
    /**
     * Get a color somewhere between startColor and endColor
     * @method between
     * @static
     * @param {String|Number} startColor 
     * @param {String|Number} endColor 
     * @param {String|Number} fraction 
     * @returns {String} a color as a hex string without '#' in front
     */
    between: function(startColor, endColor, fraction) {
        if (typeof startColor === 'string') {
            startColor = parseInt(startColor.replace('#', '0x'), 16);
        }
        if (typeof endColor === 'string') {
            endColor = parseInt(endColor.replace('#', '0x'), 16);
        }
        var startRed = (startColor >> 16) & 0xFF;
        var startGreen = (startColor >> 8) & 0xFF;
        var startBlue = startColor & 0xFF;
        var endRed = (endColor >> 16) & 0xFF;
        var endGreen = (endColor >> 8) & 0xFF;
        var endBlue = endColor & 0xFF;
        var newRed = startRed + fraction * (endRed - startRed);
        var newGreen = startGreen + fraction * (endGreen - startGreen);
        var newBlue = startBlue + fraction * (endBlue - startBlue);
        return Q.Color.toHex(newRed, newGreen, newBlue);
    },
    /**
     * Sets a new theme-color on the window
     * @method setWindowTheme
     * @static
     * @param {String} color in any CSS format, such as "#aabbcc"
     * @return {String} the previous color
     */
    setWindowTheme: function (color) {
        var meta = document.querySelector('meta[name="theme-color"]');
        var prevColor = null;
        if (meta) {
            prevColor = meta.getAttribute('content');
        }
        if (color) {
            if (!meta) {
                meta = document.createElement('meta');
                meta.setAttribute('name', 'theme-color');
            }
            meta.setAttribute('content', color);
        }
        return prevColor;
    },
    /**
     * Gets the current window theme color
     * @method getWindowTheme
     * @static
     * @param {String} color in any CSS format, such as "#aabbcc"
     * @return {String} the previous color
     */
    getWindowTheme: function () {
        var meta = document.querySelector('meta[name="theme-color"]');
        return meta.getAttribute('content');
    }
}