Created
January 6, 2014 15:37
-
-
Save unknownuser88/8284568 to your computer and use it in GitHub Desktop.
color convert RGB<==>HEX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function hex2rgb( $colour ) { | |
if ( $colour[0] == '#' ) { | |
$colour = substr( $colour, 1 ); | |
} | |
if ( strlen( $colour ) == 6 ) { | |
list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] ); | |
} elseif ( strlen( $colour ) == 3 ) { | |
list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] ); | |
} else { | |
return false; | |
} | |
$r = hexdec( $r ); | |
$g = hexdec( $g ); | |
$b = hexdec( $b ); | |
return array( 'red' => $r, 'green' => $g, 'blue' => $b ); | |
} | |
function hexToRgb(h) | |
{ | |
var r = parseInt((cutHex(h)).substring(0,2),16), g = ((cutHex(h)).substring(2,4),16), b = parseInt((cutHex(h)).substring(4,6),16) | |
return r+''+b+''+b; | |
} | |
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h} | |
//usage | |
console.log(hexToRgb("#FFFFFF")); | |
function RGB2Color(r,g,b) | |
{ | |
return '#' + this.byte2Hex(r) + this.byte2Hex(g) + this.byte2Hex(b); | |
} | |
function byte2Hex (n) | |
{ | |
var nybHexString = "0123456789ABCDEF"; | |
return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1); | |
} | |
function rgb2hex(rgb){ | |
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); | |
return "#" + | |
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) + | |
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) + | |
("0" + parseInt(rgb[3],10).toString(16)).slice(-2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment