RGB to hex and hex to RGB

前端 未结 30 2821
遥遥无期
遥遥无期 2020-11-21 06:56

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

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

相关标签:
30条回答
  • 2020-11-21 07:08

    @ Tim, to add to your answer (its a little awkward fitting this into a comment).

    As written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.

    I'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.

    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);
    }
    
    0 讨论(0)
  • 2020-11-21 07:10

    Note: both version of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.

    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);
    }
    
    alert(rgbToHex(0, 51, 255)); // #0033ff

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

    0 讨论(0)
  • 2020-11-21 07:12

    This snippet converts hex to rgb and rgb to hex.

    View demo

    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
    }
    
    0 讨论(0)
  • 2020-11-21 07:14

    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.

    0 讨论(0)
  • 2020-11-21 07:15

    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);
    
    0 讨论(0)
  • 2020-11-21 07:17

    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

    0 讨论(0)
提交回复
热议问题