Skip to content

Instantly share code, notes, and snippets.

@quickredfox
Created April 17, 2012 21:54
Show Gist options
  • Save quickredfox/2409334 to your computer and use it in GitHub Desktop.
Save quickredfox/2409334 to your computer and use it in GitHub Desktop.
HEXCHARS = '0123456789ABCDEF'.split('')
rgb2hex = (r,g,b)-> "##{byte2hex(r)}#{byte2hex(g)}#{byte2hex(b)}"
byte2hex = (n)-> String(HEXCHARS.substr((n >> 4) & 0x0F,1)) + HEXCHARS.substr(n & 0x0F,1)
hex2rgb = ( color )->
triplet = color.toLowerCase().replace /#/ , ''
rgb = []
if triplet.length is 6
rgb[0] = parseInt(triplet.substr(0,2), 16)
rgb[1] = parseInt(triplet.substr(2,2), 16)
rgb[2] = parseInt(triplet.substr(4,2), 16)
return rgb
else if triplet.length is 3
rgb[0] = parseInt((triplet.substr(0,1) + triplet.substr(0,1)), 16)
rgb[1] = parseInt((triplet.substr(1,1) + triplet.substr(1,1)), 16)
rgb[2] = parseInt((triplet.substr(2,2) + triplet.substr(2,2)), 16)
return rgb
else throw triplet + ' is not a valid color triplet.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment