Convert Hex to RGBA

Michael Schwartz picture Michael Schwartz · Feb 8, 2014 · Viewed 88.4k times · Source

My fiddle - http://jsbin.com/pitu/1/edit

I wanted to try an easy hex to rgba conversion. Ever browser I've used renders colors using rgb as default so when using the farbtastic color picker I'm converting the hex value to rgb by grabbing the background color the hex value generates (as rgb by default = simple conversion)

I tried replacing the ) symbol to , 1), but that didn't work so I went to just see how converting rgb to rgba would work, and I'm still having trouble.

The jquery

$('.torgb').val($('#color').css('background-color'));
$('.torgba').val().replace(/rgb/g,"rgba");

The goal
enter image description here

EDIT:

TinyColor Is a great color manipulation js library that does everything I want here and more. I figure you guys may want to give it a try! - https://github.com/bgrins/TinyColor

Answer

kennebec picture kennebec · Feb 8, 2014
//If you write your own code, remember hex color shortcuts (eg., #fff, #000)

function hexToRgbA(hex){
    var c;
    if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
        c= hex.substring(1).split('');
        if(c.length== 3){
            c= [c[0], c[0], c[1], c[1], c[2], c[2]];
        }
        c= '0x'+c.join('');
        return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)';
    }
    throw new Error('Bad Hex');
}

hexToRgbA('#fbafff')

/*  returned value: (String)
rgba(251,175,255,1)
*/