Skip to content

Instantly share code, notes, and snippets.

@seabre
Created October 15, 2011 02:01
Show Gist options
  • Save seabre/1288888 to your computer and use it in GitHub Desktop.
Save seabre/1288888 to your computer and use it in GitHub Desktop.
RGB Conversions
/*
rgb_hex_to_rgb_list
Example input:
rgb_hex_to_rgb_list("ffffff");
Output:
[255,255,255]
*/
function rgb_hex_to_rgb_list(hex){
var r = parseInt(hex.slice(0,2), 16);
var g = parseInt(hex.slice(2,4), 16);
var b = parseInt(hex.slice(4,6), 16);
return [r,g,b];
}
/*
rgb_list_to_rgb_hex
Example input:
rgb_list_to_rgb_hex([255,255,255]);
Output:
ffffff
*/
function rgb_list_to_rgb_hex(lst){
var r = lst[0].toString(16);
r = (r.length < 2) ? '0' + r : r;
var g = lst[1].toString(16);
g = (g.length < 2) ? '0' + g : g;
var b = lst[2].toString(16);
b = (b.length < 2) ? '0' + b : b;
return r + g + b;
}
@richardroyal
Copy link

Quick fix for maintaining leading zeros in rgb_list_to_rgb_hex(lst) :
r = (r.length < 2) ? '0'+r : r;
.
.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment