How to convert colors in RGB format to hex format and vice versa?
For example, convert \'#0080C0\'
to (0, 128, 192)
.
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