RGB to hex and hex to RGB

前端 未结 30 2769
遥遥无期
遥遥无期 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:19

    I'm assuming you mean HTML-style hexadecimal notation, i.e. #rrggbb. Your code is almost correct, except you've got the order reversed. It should be:

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

    Also, using bit-shifts might make it a bit easier to read:

    var decColor = (red << 16) + (green << 8) + blue;
    
    0 讨论(0)
  • 2020-11-21 07:20

    (2017) SIMPLE ES6 composable arrow functions

    I can't resist sharing this for those who may be writing some modern functional/compositional js using ES6. Here are some slick one-liners I am using in a color module that does color interpolation for data visualization.

    Note that this does not handle the alpha channel at all.

    const arrayToRGBString = rgb => `rgb(${rgb.join(',')})`;
    const hexToRGBArray = hex => hex.match(/[A-Za-z0-9]{2}/g).map(v => parseInt(v, 16));
    const rgbArrayToHex = rgb => `#${rgb.map(v => v.toString(16).padStart(2, '0')).join('')}`;
    const rgbStringToArray = rgb => rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).splice(1, 3)
      .map(v => Number(v));
    const rgbStringToHex = rgb => rgbArrayToHex(rgbStringToArray(rgb));
    

    BTW, If you like this style/syntax, I wrote a full color module (modern-color) you can grab from npm. I made it so I could use prop getters for conversion and parse virtually anything (Color.parse(anything)). Worth a look if you deal with color a lot like I do.

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

    // Ignoring hsl notation, color values are commonly expressed as names, rgb, rgba or hex-

    // Hex can be 3 values or 6.

    // Rgb can be percentages as well as integer values.

    // Best to account for all of these formats, at least.

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

    Considering a lot of answers only partially answer the question (either from RGB to HEX or the other way around) I thought I'd post my partial answer as well.

    I had a similar issue and I wanted to do something like this: input any valid CSS colour (HSL(a), RGB(a), HEX or colour name) and 1. be able to add or remove an alpha value, 2. return an rgb(a) object. I wrote a plugin exactly for this purpose. It can be found on GitHub (it requires jQuery, but if you want you can fork it and make a vanilla version). Here is a demo page. You can try for yourself and see the output generated on the fly.

    I'll copy-paste the options here:

    RGB Generator accepts one argument, the colour, and provides three options: asObject, addAlpha and removeAlpha. When the three options are omitted, the RGB colour will be returned as a string.

    $.rgbGenerator("white")
    // Will return rgb(255,255,255)
    

    Note that by default alpha components are included. If the input value contains an alpha value, the output will be in RGBa format.

    $.rgbGenerator("hsla(0,100%,50%,0.8)")
    // Will return rgba(255,0,0,0.8)
    

    You can disable this behaviour by setting removeAlpha to true. This will remove any alpha value from an initial HSLa or RGBa colour.

    $.rgbGenerator("hsla(0,100%,50%,0.8)", {removeAlpha: true})
    // Will return rgb(255,0,0)
    

    If, on the other hand, you want to add an alpha channel, you can do so by setting addAlpha to any value between 0 and 1. When the input is a non-transparent colour, the alpha value will be added. If it is a transparent one, the provided value will overwrite the alpha component of the input.

    $.rgbGenerator("hsl(0,100%,50%)", {addAlpha: 0.4})
    // Will return rgba(255,0,0,0.4)
    $.rgbGenerator("hsla(0,100%,50%,0.8)", {addAlpha: 0.4})
    // Will return rgba(255,0,0,0.4)
    

    Finally it's also possible to output the RGB(a) colour as an object. It will consist of r, g, b and optionally a.

    $.rgbGenerator("hsla(0,100%,50%,0.8)", {asObject: true})
    /* Will return
    {
      "r": 255,
      "g": 0,
      "b": 0,
      "a": 0.8
    }
    */
    $.rgbGenerator("hsla(0,100%,50%,0.8)", {asObject: true}).r
    // Will return 255
    
    0 讨论(0)
  • 2020-11-21 07:21

    I'm working with XAML data that has a hex format of #AARRGGBB (Alpha, Red, Green, Blue). Using the answers above, here's my solution:

    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/

    0 讨论(0)
  • 2020-11-21 07:21
    function getRGB(color){
      if(color.length == 7){
        var r = parseInt(color.substr(1,2),16);
        var g = parseInt(color.substr(3,2),16);
        var b = parseInt(color.substr(5,2),16);    
        return 'rgb('+r+','+g+','+b+')' ;
      }    
      else
        console.log('Enter correct value');
    }
    var a = getRGB('#f0f0f0');
    if(!a){
     a = 'Enter correct value'; 
    }
    
    a;
    
    0 讨论(0)
提交回复
热议问题