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

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


当前回答

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

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

其他回答

接受字符串的简写版本:

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

我为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

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

快乐编码=)

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

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

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

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