How to convert colors in RGB format to hex format and vice versa?
For example, convert \'#0080C0\'
to (0, 128, 192)
.
For 3 digits hexToRgb function of Tim Down can be improved as below:
var hex2Rgb = function(hex){
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})|([a-f\d]{1})([a-f\d]{1})([a-f\d]{1})$/i.exec(hex);
return result ? {
r: parseInt(hex.length <= 4 ? result[4]+result[4] : result[1], 16),
g: parseInt(hex.length <= 4 ? result[5]+result[5] : result[2], 16),
b: parseInt(hex.length <= 4 ? result[6]+result[6] : result[3], 16),
toString: function() {
var arr = [];
arr.push(this.r);
arr.push(this.g);
arr.push(this.b);
return "rgb(" + arr.join(",") + ")";
}
} : null;
};
i needed a function that accepts invalid values too like
rgb(-255, 255, 255) rgb(510, 255, 255)
this is a spin off of @cwolves answer
function rgb(r, g, b) {
this.c = this.c || function (n) {
return Math.max(Math.min(n, 255), 0)
};
return ((1 << 24) + (this.c(r) << 16) + (this.c(g) << 8) + this.c(b)).toString(16).slice(1).toUpperCase();
}
The top rated answer by Tim Down provides the best solution I can see for conversion to RGB. I like this solution for Hex conversion better though because it provides the most succinct bounds checking and zero padding for conversion to Hex.
function RGBtoHex (red, green, blue) {
red = Math.max(0, Math.min(~~this.red, 255));
green = Math.max(0, Math.min(~~this.green, 255));
blue = Math.max(0, Math.min(~~this.blue, 255));
return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);
};
The use of left shift '<<' and or '|' operators make this a fun solution too.
I came across this problem since I wanted to accept any color value and be able to add an opacity, so I made this quick jQuery plugin that uses the native canvas on modern browsers. Seems to work just great.
Edit
Turns out I can't figure out how to make it a proper jQuery plugin, so I'll just present it as a regular function.
//accepts any value like '#ffffff', 'rgba(255,255,255,1)', 'hsl(0,100%,100%)', or 'white'
function toRGBA( c ) {
var
can = document.createElement( 'canvas' ),
ctx = can.getContext( '2d' );
can.width = can.height = 1;
ctx.fillStyle = c;
console.log( ctx.fillStyle ); //always css 6 digit hex color string, e.g. '#ffffff'
ctx.fillRect( 0, 0, 1, 1 ); //paint the canvas
var
img = ctx.getImageData( 0, 0, 1, 1 ),
data = img.data,
rgba = {
r: data[ 0 ], //0-255 red
g: data[ 1 ], //0-255 green
b: data[ 2 ], //0-255 blue
a: data[ 3 ] //0-255 opacity (0 being transparent, 255 being opaque)
};
return rgba;
};
function hex2rgb(hex) {
return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}
May you be after something like this?
function RGB2HTML(red, green, blue)
{
return '#' + red.toString(16) +
green.toString(16) +
blue.toString(16);
}
alert(RGB2HTML(150, 135, 200));
displays #9687c8