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

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


当前回答

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

快乐编码=)

其他回答

基于@ 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, 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
}

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

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,名称颜色或十六进制值)或转换为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);

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