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:25

Shorthand version that accepts a string:

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

To check if it's not already hexadecimal

function rgbToHex(a){
  if(~a.indexOf("#"))return 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"));

查看更多
看淡一切
3楼-- · 2018-12-31 02:27

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
查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 02:28

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;
查看更多
无与为乐者.
5楼-- · 2018-12-31 02:28
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;
查看更多
看风景的人
6楼-- · 2018-12-31 02:29

This code accept #fff and #ffffff variants and opacity.

function hex2rgb(hex, opacity) {
        var h=hex.replace('#', '');
        h =  h.match(new RegExp('(.{'+h.length/3+'})', 'g'));

        for(var i=0; i<h.length; i++)
            h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16);

        if (typeof opacity != 'undefined')  h.push(opacity);

        return 'rgba('+h.join(',')+')';
}
查看更多
长期被迫恋爱
7楼-- · 2018-12-31 02:29
function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}
查看更多
登录 后发表回答