Skip to content

Instantly share code, notes, and snippets.

@junaidpv
Created July 31, 2013 07:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save junaidpv/6119929 to your computer and use it in GitHub Desktop.
Save junaidpv/6119929 to your computer and use it in GitHub Desktop.
Javascript RGB(A) string conversion functions.
/**
* Parse an rgb or rgba string like 'rgb(67, 216, 89)' or 'rgba(245, 156, 8, 178)'
* to array of integers in the order.
* Credit: http://stackoverflow.com/questions/10970958/get-a-color-component-from-an-rgb-string-in-javascript
**/
function parse_rgb_string(rgb) {
rgb = rgb.replace(/[^\d,]/g, '').split(',');
return rgb;
}
/**
* Create and hexadecimal string corresponding to given deciman number.
**/
function dec_to_hex_string(dec, length) {
var hex = dec.toString(16).toUpperCase();
if (hex.length < length) {
hex = new Array( length - hex.length + 1 ).join( '0' ) + hex;
}
return hex;
}
function rgba_to_hex_string(rgb_string, alpha_percentage) {
var rgb_array = parse_rgb_string(rgb_string);
if (typeof alpha_percentage !== 'undefined') {
var alpha = 255 * alpha_percentage / 100;
alpha = Math.floor(alpha);
// Apply alpha value replacing existing if there.
rgb_array[3] = alpha;
}
var hex_string = '';
for( var i = 0; i < rgb_array.length; i++) {
hex_string += dec_to_hex_string(rgb_array[i], 2);
}
return '#' + hex_string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment