Skip to content

Instantly share code, notes, and snippets.

@jasonclemons
Created July 3, 2012 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonclemons/3040167 to your computer and use it in GitHub Desktop.
Save jasonclemons/3040167 to your computer and use it in GitHub Desktop.
Simple RGB->Hex and Hex->RGB converter.
<?php
/**
* HEX to RGB and RGB to HEX converter
* Thanks to hafees@msn.com on php.net for the base
* http://www.php.net/manual/en/function.hexdec.php#99478
*/
/**
* Convert an RGB array to HEX
*
* @param array $colors array('r' => 255, 'g' => 125, 'b' => 0)
* @return string
*/
function rgb_to_hex($colors = array()) {
/* Won't accept black, so we make an exception (thanks Arantor) */
if ($colors['r'] === '0' && $colors['g'] === '0' && $colors['b'] === '0')
return '000000';
/* If it's an empty array, or missing a color, it's invalid! */
if (empty($colors['r']) && empty($colors['g']) & empty($colors['b']))
return false;
return strtoupper(dechex($colors['r']).dechex($colors['g']).dechex($colors['b']));
}
/**
* Convert a HEX color string to an RGB array
*
* @param string $hex HEX string to convert
* @param bool $returnstring Return as string or array
* @return array
*/
function hex_to_rgb($hex, $returnstring = false) {
$hex = preg_replace('~[^0-9A-Fa-f]~', '', $hex);
$rgb = array();
if (strlen($hex) == 6) {
$color = hexdec($hex);
$rgb['r'] = 0xFF & ($color >> 0x10);
$rgb['g'] = 0xFF & ($color >> 0x8);
$rgb['b'] = 0xFF & $color;
} elseif (strlen($hex) == 3) {
$rgb['r'] = hexdec(str_repeat(substr($hex, 0, 1), 2));
$rgb['g'] = hexdec(str_repeat(substr($hex, 1, 1), 2));
$rgb['b'] = hexdec(str_repeat(substr($hex, 2, 1), 2));
} else
return false;
return $returnstring == true ? implode(',', $rgb) : $rgb;
}
echo rgb_to_hex(array('r' => '0', 'g' => '0', 'b' => '0'));
echo '<br />';
echo hex_to_rgb('1234ef', true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment