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

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


当前回答

//忽略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));

其他回答

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

循环数组 使用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("");
}

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

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>

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

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

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

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

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