How to convert colors in RGB format to hex format and vice versa?
For example, convert \'#0080C0\'
to (0, 128, 192)
.
My version of hex2rbg:
String.replace, String.split, String.match
etc..you may need remove hex.trim() if you are using IE8.
e.g.
hex2rgb('#fff') //rgb(255,255,255)
hex2rgb('#fff', 1) //rgba(255,255,255,1)
hex2rgb('#ffffff') //rgb(255,255,255)
hex2rgb('#ffffff', 1) //rgba(255,255,255,1)
code:
function hex2rgb (hex, opacity) {
hex = hex.trim();
hex = hex[0] === '#' ? hex.substr(1) : hex;
var bigint = parseInt(hex, 16), h = [];
if (hex.length === 3) {
h.push((bigint >> 4) & 255);
h.push((bigint >> 2) & 255);
} else {
h.push((bigint >> 16) & 255);
h.push((bigint >> 8) & 255);
}
h.push(bigint & 255);
if (arguments.length === 2) {
h.push(opacity);
return 'rgba('+h.join()+')';
} else {
return 'rgb('+h.join()+')';
}
}