RGB to Hex and Hex to RGB

2018-12-31 01:50发布

How to convert colors in RGB format to Hex format and vice versa?

For example, convert '#0080C0' to (0, 128, 192).

30条回答
春风洒进眼中
2楼-- · 2018-12-31 02:13

The top rated answer by Tim Down provides the best solution I can see for conversion to RGB. I like this solution for Hex conversion better though because it provides the most succinct bounds checking and zero padding for conversion to Hex.

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

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

The use of left shift '<<' and or '|' operators make this a fun solution too.

查看更多
人气声优
3楼-- · 2018-12-31 02:15

The following will do to the RGB to hex conversion and add any required zero padding:

function componentToHex(c) {
    var hex = c.toString(16);
    return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
    return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert( rgbToHex(0, 51, 255) ); // #0033ff

Converting the other way:

function hexToRgb(hex) {
    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";

Finally, an alternative version of rgbToHex(), as discussed in @casablanca's answer and suggested in the comments by @cwolves:

function rgbToHex(r, g, b) {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

Update 3 December 2012

Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#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";
查看更多
像晚风撩人
4楼-- · 2018-12-31 02:15

For 3 digits hexToRgb function of Tim Down can be improved as below:

var hex2Rgb = function(hex){
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})|([a-f\d]{1})([a-f\d]{1})([a-f\d]{1})$/i.exec(hex);
  return result ? {        
    r: parseInt(hex.length <= 4 ? result[4]+result[4] : result[1], 16),
    g: parseInt(hex.length <= 4 ? result[5]+result[5] : result[2], 16),
    b: parseInt(hex.length <= 4 ? result[6]+result[6] : result[3], 16),
    toString: function() {
      var arr = [];
      arr.push(this.r);
      arr.push(this.g);
      arr.push(this.b);
      return "rgb(" + arr.join(",") + ")";
    }
  } : null;
};
查看更多
不再属于我。
5楼-- · 2018-12-31 02:16

While this answer is unlikely to fit the question perfectly it may be very useful none the less.

  1. Create any random element

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

  1. Set any valid style to the color you want to convert

toRg.style.color = "hsl(120, 60%, 70%)";

  1. Call the style property again

> toRgb.style.color;

< "rgb(133, 225, 133)" Your color has been converted to Rgb

Works for: Hsl, Hex

Does not work for: Named colors

查看更多
其实,你不懂
6楼-- · 2018-12-31 02:17

ECMAScript 6 version of Tim Down's answer

Converting RGB to hex

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

console.log(rgbToHex(0, 51, 255)); // '#0033ff'

Converting hex to RGB

Returns an array [r, g, b]. Works also with shorthand hex triplets such as "#03F".

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

Bonus: RGB to hex using padStart() method

const rgbToHex = (r, g, b) => '#' + [r, g, b]
  .map(x => x.toString(16).padStart(2, '0')).join('')

console.log(rgbToHex(0, 51, 255)); // '#0033ff'

Note that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code.

查看更多
人气声优
7楼-- · 2018-12-31 02:17

If you need compare two color values (given as rgb,name color or hex value) or convert to HEX use HTML5 canvas object.

    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);
查看更多
登录 后发表回答