Skip to content

Instantly share code, notes, and snippets.

@Pushplaybang
Created April 22, 2013 06:35
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save Pushplaybang/5432844 to your computer and use it in GitHub Desktop.
Save Pushplaybang/5432844 to your computer and use it in GitHub Desktop.
php functions convert hex to rgb and rgb to hex
function hex2rgb($hex) {
$hex = str_replace("#", "", $hex);
if(strlen($hex) == 3) {
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
} else {
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
}
$rgb = array($r, $g, $b);
//return implode(",", $rgb); // returns the rgb values separated by commas
return $rgb; // returns an array with the rgb values
}
function rgb2hex($rgb) {
$hex = "#";
$hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT);
return $hex; // returns the hex value including the number sign (#)
}
@iamkiros
Copy link

iamkiros commented Oct 5, 2014

We can do rgb2hex($rgb) simplier

function rgb2hex($rgb)
{
return '#' . sprintf('%02x', $rgb['r']) . sprintf('%02x', $rgb['g']) . sprintf('%02x', $rgb['b']);
}

@votemike
Copy link

For hex2rgb you could do

function hex2rgb($hex) {
   $hex = str_replace("#", "", $hex);

   if(strlen($hex) == 3) {
      $r = hexdec($hex[0].$hex[0]);
      $g = hexdec($hex[1].$hex[1]);
      $b = hexdec($hex[2].$hex[2]);
   } else {
      $r = hexdec($hex[0].$hex[1]);
      $g = hexdec($hex[2].$hex[3]);
      $b = hexdec($hex[4].$hex[5]);
   }

   return array($r, $g, $b); // returns an array with the rgb values
}

@calshox
Copy link

calshox commented Aug 26, 2016

For hex2rgb you can do:

function hex2rgb($hex) { return sscanf($hex, "#%02x%02x%02x"); }

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