ChatGPT解决这个技术问题 Extra ChatGPT

RGB to hex and hex to RGB

How to convert colors in RGB format to hex format and vice versa?

For example, convert '#0080C0' to (0, 128, 192).

Here' are functions for RGB<->Hex conversation, Average of 2 hex colors, and Random hex color.

T
Tim Down

Note: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.

The following will do to the RGB to hex conversion and add any required zero padding:

function componentToHex(c) { var hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } function rgbToHex(r, g, b) { return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); } alert(rgbToHex(0, 51, 255)); // #0033ff

Converting the other way:

function hexToRgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } alert(hexToRgb("#0033ff").g); // "51";

Finally, an alternative version of rgbToHex(), as discussed in @casablanca's answer and suggested in the comments by @cwolves:

function rgbToHex(r, g, b) { return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); } alert(rgbToHex(0, 51, 255)); // #0033ff

Update 3 December 2012

Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#03F":

function hexToRgb(hex) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } alert(hexToRgb("#0033ff").g); // "51"; alert(hexToRgb("#03f").g); // "51";


@Vitim.us: << is the bitwise left shift operator. Assuming g is a non-zero integer, g << 8 therefore effectively multiplies g by 256, adding to zeroes to the end of its hex representation. Likewise r << 16 adds 4 zeroes. Adding 1 << 24 (1000000 in hex) ensures that the hex representation is left-padded with any required zeroes once the leading 1 is stripped off using slice(). For example, if r and g were both zero and b was 51, ((r << 16) + (g << 8) + b).toString(16) would return the string "33"; add 1 << 24 and you get "1000033". Then strip the 1 and you're there.
Would the bit shifting (eg (r << 16)) give the same result on both big and little endian computers? Edit: It does not. Here's why: stackoverflow.com/questions/1041554/…
your rgbToHex doesn't work. get the funny result: #f55b2f00
Regarding the latest rgbToHex function. One will want to either typecast your passed rgb values as integers, or slightly modify the rgbToHex function. Example: jsfiddle.net/cydqo6wj Current: return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); Modified: return "#" + ((1 << 24) + ((+r) << 16) + ((+g) << 8) + (+b)).toString(16).slice(1); In the modified version, I simply force the rgb values to be evalued at integers prior to the change over to 16/hex.
@RobinMétral: That's the full string matched by the regular expression. r, g and b correspond to the capturing groups, which is the stuff we actually want.
d
dtasev

An alternative version of hexToRgb:

function hexToRgb(hex) {
    var bigint = parseInt(hex, 16);
    var r = (bigint >> 16) & 255;
    var g = (bigint >> 8) & 255;
    var b = bigint & 255;

    return r + "," + g + "," + b;
}

Edit: 3/28/2017 Here is another approach that seems to be even faster

function hexToRgbNew(hex) {
  var arrBuff = new ArrayBuffer(4);
  var vw = new DataView(arrBuff);
  vw.setUint32(0,parseInt(hex, 16),false);
  var arrByte = new Uint8Array(arrBuff);

  return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}

Edit: 8/11/2017 The new approach above after more testing is not faster :(. Though it is a fun alternate way.


A line of perfection: return [r, g, b].join();.
Or for the all-encapsulating one-liner solution: return [(bigint = parseInt(hex, 16)) >> 16 & 255, bigint >> 8 & 255, bigint & 255].join();
I am using this with one tweak - remove non-hex chars (like a leading #) before parseInt: hex = hex.replace(/[^0-9A-F]/gi, '');
Don't be so quick to use the shorthand version. JSPerf shows that the one in this answer is fastest: jsperf.com/2014-09-16-hex-to-rgb
Be careful with this, its output isn't reliable. It made a color close to black appear dark pink. Better to use the function from top answer.
M
Michał Perłakowski

ECMAScript 6 version of Tim Down's answer

Converting RGB to hex

const rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => { const hex = x.toString(16) return hex.length === 1 ? '0' + hex : hex }).join('') console.log(rgbToHex(0, 51, 255)); // '#0033ff'

Converting hex to RGB

Returns an array [r, g, b]. Works also with shorthand hex triplets such as "#03F".

const hexToRgb = hex => hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i ,(m, r, g, b) => '#' + r + r + g + g + b + b) .substring(1).match(/.{2}/g) .map(x => parseInt(x, 16)) console.log(hexToRgb("#0033ff")) // [0, 51, 255] console.log(hexToRgb("#03f")) // [0, 51, 255]

Bonus: RGB to hex using padStart() method

const rgbToHex = (r, g, b) => '#' + [r, g, b] .map(x => x.toString(16).padStart(2, '0')).join('') console.log(rgbToHex(0, 51, 255)); // '#0033ff'

Note that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code.


hexToRgb() is easily adapted to handle 4 and 8 digit hex RGBA notation: .replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(m, r, g, b) => '#' + r + r + g + g + b + b) becomes: .replace(/^#?([a-f\d])([a-f\d])([a-f\d])([a-f\d])$/i,(m, r, g, b, a) => '#' + r + r + g + g + b + b + a + a) But is there a way to make the regexp work with A of RGBA as an optional 4th hex value? That would absolutely complete the functionality, making one regexp work with hex RGB and RGBA. Otherwise it's two regexps, one with 3 values, the other with 4. You must divide the 4th value by 255 to get the 4th arg for rgba().
const rgbToHex = (rgb) => { const rgbExcludeFirst = rgb.split('rgb(')[1]; const rgbExcludeLast = rgbExcludeFirst.split(')')[0]; const rgbValueArray = rgbExcludeLast.split(','); return `#${rgbValueArray.map((x) => { const valAsInt = parseInt(x, 10); const hex = valAsInt.toString(16); return hex.length === 1 ? `0${hex}` : hex; }).join('')}`; }; if you want to pass an RGB string in
F
FelipeC

Here's my version:

function rgbToHex(red, green, blue) {
  const rgb = (red << 16) | (green << 8) | (blue << 0);
  return '#' + (0x1000000 + rgb).toString(16).slice(1);
}

function hexToRgb(hex) {
  const normal = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
  if (normal) return normal.slice(1).map(e => parseInt(e, 16));

  const shorthand = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
  if (shorthand) return shorthand.slice(1).map(e => 0x11 * parseInt(e, 16));

  return null;
}

A little bit confused about the rgb2hex method. Why do we add 0x1000000 to rgb, and why we need to call .slice(1) at last?
Because blue would be #FF, we add 0x1000000, so it's #10000FF, and then we remove the first "1".
this also worked for me, when the other examples on this page didnt. i wanted to convert RGB 100, 100, 100 to HEX, other examples on this page returned "#100100100" - whilst this example, correctly returned "#646464"
r
rezoner
function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}

I love simple answers
Witchcraft! you should add an explanation to this very cool one-liner.
Nice! Here's the same thing, except minified and returning an object with properties r,g,b : function hex2rgb(hex){return{r:'0x'+hex[1]+hex[2]|0,g:'0x'+hex[3]+hex[4]|0,b:'0x'+hex[5]+hex[6]|0}}
Very nice. Doesnt work with shorthand but neat. handles the hash without the ugly subscript.
c
casablanca

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;

Great, except you need to left zero-pad it to 6 characters if red<16: var decColor = (red < 16 ? '0' : '') + (red << 16) + (green << 8) + blue;
Seems to works except for this :(0,128,192) probably because of the 0 ?
@cwolves: You're right, I missed that. But it should be appended to the final string, not the integer.
@Sindar: See @cwolves' comment, if red < 16 you need to prefix a 0 to the final result.
okay, HERE: var hexColor = ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).substr(1);
D
Denis

One-line functional HEX to RGBA

Supports both short #fff and long #ffffff forms.
Supports alpha channel (opacity).
Does not care if hash specified or not, works in both cases.

function hexToRGBA(hex, opacity) {
    return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(isFinite(opacity) ? opacity : 1).join(',') + ')';
}

examples:

hexToRGBA('#fff')        ->  rgba(255,255,255,1)  
hexToRGBA('#ffffff')     ->  rgba(255,255,255,1)  
hexToRGBA('#fff', .2)    ->  rgba(255,255,255,0.2)  
hexToRGBA('#ffffff', .2) ->  rgba(255,255,255,0.2)  
hexToRGBA('fff', .2)     ->  rgba(255,255,255,0.2)  
hexToRGBA('ffffff', .2)  ->  rgba(255,255,255,0.2)

hexToRGBA('#ffffff', 0)  ->  rgba(255,255,255,0)
hexToRGBA('#ffffff', .5) ->  rgba(255,255,255,0.5)
hexToRGBA('#ffffff', 1)  ->  rgba(255,255,255,1)

Try to write human-readable code, not one-liners. There's no gain if you minify your code before production anyways.
This is what used. Good job! Only thing I added (apart from arrow function conversion) was (hex, opacity = 1). Yours would convert 0 to 1 which may not produce expected results.
This is very readable code. I do not share the sentiment.
Adrian Bartholomew, great catch! fixed
this is a good one liner code and readable. If you want it in multiline then throw it in a formatter.
K
Kamil Kiełczewski

Try (bonus)

let hex2rgb= c=> `rgb(${c.match(/\w\w/g).map(x=>+`0x${x}`)})`
let rgb2hex=c=>'#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``

let hex2rgb= c=> `rgb(${c.match(/\w\w/g).map(x=>+`0x${x}`)})`; let rgb2hex= c=> '#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``; // TEST console.log('#0080C0 -->', hex2rgb('#0080C0')); console.log('rgb(0, 128, 192) -->', rgb2hex('rgb(0, 128, 192)'));


Nice! I use the following code to calculate the berightness level of the color (e.g. whether the color is dark or light to identify the text color for use with it.) Here's the code in Javascript to get the luminance: let rgb = color.match(/\w\w/g).map(x=>+`0x${x}`); let lum = (rgb[0]*0.299 + rgb[1]*0.587 + rgb[2]*0.114) / 256; lum > 0.5 is light/bright color
@Aryo according to wiki luminance (from hsl) is L = (max(R,G,B) + min(R,G,B))/2 - but I not test it. May be your formula is more based on eye physical properties...
Yes, the formula is not the actual formula for luminance. Using the actual luminance formula. Blue is somehow perceived darker than green/yellow at the same luminance level. So, there must be something to be changed from each color component. I got the code from here: stackoverflow.com/a/1754281/764788 which measure the brightness level according to a human perceived brightness level of each R, G, and B color and weight each of them respectively.
f
falko

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(',')+')';
}

m
macabeus

Bitwise solution normally is weird. But in this case I guess that is more elegant 😄

function hexToRGB(hexColor){
  return {
    red: (hexColor >> 16) & 0xFF,
    green: (hexColor >> 8) & 0xFF,  
    blue: hexColor & 0xFF,
  }
}

Usage:

const {red, green, blue } = hexToRGB(0xFF00FF)

console.log(red) // 255
console.log(green) // 0
console.log(blue) // 255

R
Ron Gilchrist

(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.


K
K-Gun

This could be used for getting colors from computed style propeties:

function rgbToHex(color) {
    color = ""+ color;
    if (!color || color.indexOf("rgb") < 0) {
        return;
    }

    if (color.charAt(0) == "#") {
        return color;
    }

    var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color),
        r = parseInt(nums[2], 10).toString(16),
        g = parseInt(nums[3], 10).toString(16),
        b = parseInt(nums[4], 10).toString(16);

    return "#"+ (
        (r.length == 1 ? "0"+ r : r) +
        (g.length == 1 ? "0"+ g : g) +
        (b.length == 1 ? "0"+ b : b)
    );
}

// not computed 
<div style="color: #4d93bc; border: 1px solid red;">...</div> 
// computed 
<div style="color: rgb(77, 147, 188); border: 1px solid rgb(255, 0, 0);">...</div>

console.log( rgbToHex(color) ) // #4d93bc
console.log( rgbToHex(borderTopColor) ) // #ff0000

Ref: https://github.com/k-gun/so/blob/master/so_util.js


Thank you for this. But there's a small error: should return (r.length == 1 ? "0" + r : r) and similarly for green and blue.
C
Carson

Hex to RGB

const hex2rgb = (hex) => { const r = parseInt(hex.slice(1, 3), 16) const g = parseInt(hex.slice(3, 5), 16) const b = parseInt(hex.slice(5, 7), 16) // return {r, g, b} // return an object return [ r, g, b ] } console.log(hex2rgb("#0080C0"))

RGB to Hex

const rgb2hex = (r, g, b) => { var rgb = (r << 16) | (g << 8) | b // return '#' + rgb.toString(16) // #80c0 // return '#' + (0x1000000 + rgb).toString(16).slice(1) // #0080c0 // or use [padStart](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) return '#' + rgb.toString(16).padStart(6, 0) } console.log(rgb2hex(0, 128, 192))

Also if someone need online tool, I have built Hex to RGB and vice versa.


When linking to your own site or content (or content that you are affiliated with), you must disclose your affiliation in the answer in order for it not to be considered spam. Having the same text in your username as the URL or mentioning it in your profile is not considered sufficient disclosure under Stack Exchange policy.
As @cigien says - I have edited your post to make the affiliation explicit.
k
kennebec

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

Upvoted for this being the most comprehensive version I've looked at. It'd be great if it could extract the colours from rgba, too.
M
Miquel

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


> RGB2HTML > 2HTML > TO HTML ( ಠ ʖ̯ ಠ) HEX is not related to HTML
M
Matt Stevens

@ Tim, to add to your answer (its a little awkward fitting this into a comment).

As written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.

I'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.

function rgbToHex(r, g, b) {
    if(r < 0 || r > 255) alert("r is out of bounds; "+r);
    if(g < 0 || g > 255) alert("g is out of bounds; "+g);
    if(b < 0 || b > 255) alert("b is out of bounds; "+b);
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
}

M
Moshe Slavin

If you need compare two color values (given as RGB, name color or hex value) or convert to HEX use HTML5 canvas object.

var canvas = document.createElement("canvas");
var ctx = this.canvas.getContext('2d');

ctx.fillStyle = "rgb(pass,some,value)";
var temp =  ctx.fillStyle;
ctx.fillStyle = "someColor";

alert(ctx.fillStyle == temp);

this is a grate way to convert any css color format and normalize it to hex, don't work in node unfortally but you could take adv of offscreenCanvas for web workers
d
deadcoder0904

2021 version

You can simply use rgb-hex & hex-rgb as it is battle-tested & has multiple options that are not available in other solutions.

I was recently building a Color Picker & these 2 packages came in handy.

Usage

rgb-hex

import rgbHex from 'rgb-hex';

rgbHex(65, 131, 196);
//=> '4183c4'

rgbHex('rgb(40, 42, 54)');
//=> '282a36'

rgbHex(65, 131, 196, 0.2);
//=> '4183c433'

rgbHex(40, 42, 54, '75%');
//=> '282a36bf'

rgbHex('rgba(40, 42, 54, 75%)');
//=> '282a36bf'

hex-rgb

import hexRgb from 'hex-rgb';

hexRgb('4183c4');
//=> {red: 65, green: 131, blue: 196, alpha: 1}

hexRgb('#4183c4');
//=> {red: 65, green: 131, blue: 196, alpha: 1}

hexRgb('#fff');
//=> {red: 255, green: 255, blue: 255, alpha: 1}

hexRgb('#22222299');
//=> {red: 34, green: 34, blue: 34, alpha: 0.6}

hexRgb('#0006');
//=> {red: 0, green: 0, blue: 0, alpha: 0.4}

hexRgb('#cd2222cc');
//=> {red: 205, green: 34, blue: 34, alpha: 0.8}

hexRgb('#cd2222cc', {format: 'array'});
//=> [205, 34, 34, 0.8]

hexRgb('#cd2222cc', {format: 'css'});
//=> 'rgb(205 34 34 / 80%)'

hexRgb('#000', {format: 'css'});
//=> 'rgb(0 0 0)'

hexRgb('#22222299', {alpha: 1});
//=> {red: 34, green: 34, blue: 34, alpha: 1}

hexRgb('#fff', {alpha: 0.5});
//=> {red: 255, green: 255, blue: 255, alpha: 0.5}

A
Aart den Braber

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


C
Chad Scira

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();
}

u
user3767878
R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");

function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

Use these Function to achive the result without any issue. :)


n
nachtigall

Instead of copy'n'pasting snippets found here and there, I'd recommend to use a well tested and maintained library: Colors.js (available for node.js and browser). It's just 7 KB (minified, gzipped even less).


Thank god someone suggested to use a library instead of copy-pasting untested code. Here is one more library with recent updates: npmjs.com/package/hex-rgb
P
Patrick Roberts

I came across this problem since I wanted to parse any color string value and be able to specify an opacity, so I wrote this function that uses the canvas API.

var toRGBA = function () {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  canvas.width = 1;
  canvas.height = 1;

  return function (color) {
    context.fillStyle = color;
    context.fillRect(0, 0, 1, 1);

    var data = context.getImageData(0, 0, 1, 1).data;

    return {
      r: data[0],
      g: data[1],
      b: data[2],
      a: data[3]
    };
  };
}();

Note about context.fillStyle:

If parsing the value results in failure, then it must be ignored, and the attribute must retain its previous value.

Here's a Stack Snippet demo you can use to test inputs:

var toRGBA = function () { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.width = 1; canvas.height = 1; return function (color) { context.fillStyle = color; context.fillRect(0, 0, 1, 1); var data = context.getImageData(0, 0, 1, 1).data; return { r: data[0], g: data[1], b: data[2], a: data[3] }; }; }(); var inputs = document.getElementsByTagName('input'); function setColor() { inputs[1].value = JSON.stringify(toRGBA(inputs[0].value)); document.body.style.backgroundColor = inputs[0].value; } inputs[0].addEventListener('input', setColor); setColor(); input { width: 200px; margin: 0.5rem; }


R
Roopesh

A simple answer to convert RGB to hex. Here values of color channels are clamped between 0 and 255.

function RGBToHex(r = 0, g = 0, b = 0) {
    // clamp and convert to hex
    let hr = Math.max(0, Math.min(255, Math.round(r))).toString(16);
    let hg = Math.max(0, Math.min(255, Math.round(g))).toString(16);
    let hb = Math.max(0, Math.min(255, Math.round(b))).toString(16);
    return "#" +
        (hr.length<2?"0":"") + hr +
        (hg.length<2?"0":"") + hg +
        (hb.length<2?"0":"") + hb;
}

E
Entarra De'Lacord

While this answer is unlikely to fit the question perfectly it may be very useful none the less.

Create any random element

var toRgb = document.createElement('div');

Set any valid style to the color you want to convert

toRg.style.color = "hsl(120, 60%, 70%)";

Call the style property again

> toRgb.style.color;

< "rgb(133, 225, 133)" Your color has been converted to Rgb

Works for: Hsl, Hex

Does not work for: Named colors


This may be the most practical answer when working with the browser. You often simply want to compare the color of some existing element to some known color expressed in #-notation.
E
Eric Chen

My version of hex2rbg:

Accept short hex like #fff Algorithm compacity is o(n), should faster than using regex. e.g String.replace, String.split, String.match etc.. Use constant space. Support rgb and rgba.

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()+')';
    }
}

Note that h.join(',') is the same thing as h.join().
k
khaki

This snippet converts hex to rgb and rgb to hex.

View demo

function hexToRgb(str) { 
    if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(str) ) { 
        var hex = str.substr(1);
        hex = hex.length == 3 ? hex.replace(/(.)/g, '$1$1') : hex;
        var rgb = parseInt(hex, 16);               
        return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';
    } 

    return false; 
}

function rgbToHex(red, green, blue) {
    var out = '#';

    for (var i = 0; i < 3; ++i) {
        var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);

        if (isNaN(n) || n < 0 || n > 255) {
            return false;
        }

        out += (n < 16 ? '0' : '') + n.toString(16);
    }
    return out
}

Good as it handles shorthand, but could it return a structure rather than a string?
O
Oliver Cape

2022: If you often manipulate colors and doesn't mind using a package,

Use tinycolor2. It's a fast library (Around 400kb) for color manipulation and conversion in JavaScript.

It accepts various color string format. Like:

tinycolor("#000"); // Hex3
tinycolor("#f0f0f6"); // Hex6
tinycolor("#f0f0f688"); // Hex8
tinycolor("f0f0f6"); // Hex withouth the number sign '#'
tinycolor("rgb (255, 0, 0)"); // RGB
tinycolor("rgba (255, 0, 0, .5)"); // RGBA
tinycolor({ r: 255, g: 0, b: 0 }); // RGB object
tinycolor("hsl(0, 100%, 50%)"); // HSL
tinycolor("hsla(0, 100%, 50%, .5)"); // HSLA
tinycolor("red"); // Named

RGB to HEX

var color = tinycolor('rgb(0, 128, 192)');
color.toHexString(); //#0080C0

HEX to RGB

var color = tinycolor('#0080C0');
color.toRgbString(); // rgb(0, 128, 192)

Visit documentation for more demo.


Something to note about this library that's really cool is that it also allows you to validate the input.
o
onitake

Looks like you're looking for something like this:

function hexstr(number) {
    var chars = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
    var low = number & 0xf;
    var high = (number >> 4) & 0xf;
    return "" + chars[high] + chars[low];
}

function rgb2hex(r, g, b) {
    return "#" + hexstr(r) + hexstr(g) + hexstr(b);
}

var chars = "0123456789abcdef"; easier.
B
Benson

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/