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

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


当前回答

对于直接从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'))

其他回答

建立了我自己的十六进制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;

快乐编码=)

我正在使用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/

一行功能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)

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

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