Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Mathematical Functions : hexdec

hexdec

Hexadecimal to decimal (PHP 4, PHP 5)
number hexdec ( string hex_string )

Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. hexdec() converts a hexadecimal string to a decimal number.

hexdec() will ignore any non-hexadecimal characters it encounters.

Parameters

hex_string

The hexadecimal string to convert

Return Values

The decimal representation of hex_string

ChangeLog

Version Description
Since 4.1.0 The function can now convert values that are to big for the platforms integer type, it will return the value as float instead in that case.

Examples

Example 1149. hexdec() example

<?php
var_dump
(hexdec("See"));
var_dump(hexdec("ee"));
// both print "int(238)"

var_dump(hexdec("that")); // print "int(10)"
var_dump(hexdec("a0")); // print "int(160)"
?>


Related Examples ( Source code ) » hexdec




Code Examples / Notes » hexdec

rledger

To convert a cellular ESN from hexadecimal to decimal, use the following code. The base conversion is different due to the fact that the first two characters of a hexadecimal value must be converted seperately from the remaining six characters.
<?
function esnhexdec($hex){
  $a = sprintf("%03d", hexdec(substr($hex, 0, 2)));
  $b = sprintf("%08d", hexdec(substr($hex, 2, 6)));
  return $a . $b;
}
?>


manithu

This tiny function will return foreground colors (either black or white) in contrast to the color you provide:
<?php
function getContrastColor($color)
{
return (hexdec($color) > 0xffffff/2) ? '000000' : 'ffffff';
}
?>
This function will return the opposite (negative):
<?php
function negativeColor($color)
{
//get red, green and blue
$r = substr($color, 0, 2);
$g = substr($color, 2, 2);
$b = substr($color, 4, 2);

//revert them, they are decimal now
$r = 0xff-hexdec($r);
$g = 0xff-hexdec($g);
$b = 0xff-hexdec($b);

//now convert them to hex and return.
return dechex($r).dechex($g).dechex($b);
}
?>


zubfatal, root

This replaces my previous class.
I've added a few more input checks in the rgb2hex function.
Also it returned incorrect hex values for 1-digit values.
color::rgb2hex(array(0,0,0)) would output 000 not 00000.
<?php
/**
* Convert colors
*
* Usage:
*  color::hex2rgb("FFFFFF")
*  color::rgb2hex(array(171,37,37))
*
* @author      Tim Johannessen <root@it.dk>
* @version     1.0.1
*/
class color {
   /**
    * Convert HEX colorcode to an array of colors.
    * @return      array        Returns the array of colors as array(red,green,blue)
    */
   
   function hex2rgb($hexVal = "") {
       $hexVal = eregi_replace("[^a-fA-F0-9]", "", $hexVal);
       if (strlen($hexVal) != 6) { return "ERR: Incorrect colorcode, expecting 6 chars (a-f, 0-9)"; }
       $arrTmp = explode(" ", chunk_split($hexVal, 2, " "));
       $arrTmp = array_map("hexdec", $arrTmp);
       return array("red" => $arrTmp[0], "green" => $arrTmp[1], "blue" => $arrTmp[2]);
   }
   
   /**
    * Convert RGB colors to HEX colorcode
    * @return      string        Returns the converted colors as a 6 digit colorcode
    */
   function rgb2hex($arrColors = null) {
       if (!is_array($arrColors)) { return "ERR: Invalid input, expecting an array of colors"; }
       if (count($arrColors) < 3) { return "ERR: Invalid input, array too small (3)"; }
       
       array_splice($arrColors, 3);
       
       for ($x = 0; $x < count($arrColors); $x++) {
           if (strlen($arrColors[$x]) < 1) {
               return "ERR: One or more empty values found, expecting array with 3 values";
           }
           
           elseif (eregi("[^0-9]", $arrColors[$x])) {
               return "ERR: One or more non-numeric values found.";
           }
           
           else {
               if ((intval($arrColors[$x]) < 0) || (intval($arrColors[$x]) > 255)) {
                   return "ERR: Range mismatch in one or more values (0-255)";
               }
               
               else {
                   $arrColors[$x] = strtoupper(str_pad(dechex($arrColors[$x]), 2, 0, STR_PAD_LEFT));
               }
           }
       }
       
       return implode("", $arrColors);
   }
}
?>


hajamie@home

This function will take a hex $color, e.g. fa34bc and make it the shade you want, e.g. anywhere between 0 and 255. The smaller the number, the darker the output color.  It keeps the color the same, only changing the shade.  
function correctshade($color, $shade)
{
$r = hexdec(substr($color,0,2));
$g = hexdec(substr($color,2,2));
$b = hexdec(substr($color,4,2));
$sum = ($r + $g + $b);
$x = (($shade * 3) - $sum) / $sum;
if ($x >= 0) {
$x = $x + 1;
} else {
$x = 1 + $x;
}
$r = intval($x * $r);
$g = intval($x * $g);
$b = intval($x * $b);
$r = dechex($r);
$g = dechex($g);
$b = dechex($b);
return $r.$g.$b;
}


brian

The issue I've seen with the existing hex to dec conversion routines is the lack of error-trapping.  I stick to the theory that one should try to cover ALL the bases when writing a generalized routine such as this one.  I have a varied background that covers a wide variety of design/development languages, on the web as well as desktop apps.  As such I've seen multiple formats for writing hex colors.
For example, the color red COULD be written as follows:
#ff0000
&Hff0000
#ff
&Hff
Therefore I have written a function that is case-insensitive and takes into account the chance that different developers have a tendency to format hex colors in different ways.
<?php
 function convert_color($hex){
   $len = strlen($hex);
   $chars = array("#","&","H","h");
   $hex = strip_chars($hex, $chars);
   preg_match("/([0-9]|[A-F]|[a-f]){".$len."}/i",$hex,$arr);
   $hex = $arr[0];
   if ($hex) {
     switch($len) {
       case 2:
         $red = hexdec($hex);
         $green = 0;
         $blue = 0;
         break;
       case 4:
         $red = hexdec(substr($hex,0,2));
         $green=hexdec(substr($hex,2,2));
         $blue = 0;
         break;
       case 6:
         $red = hexdec(substr($hex,0,2));
         $green=hexdec(substr($hex,2,2));
         $blue = hexdec(substr($hex,4,2));
         break;      
     };
     $color[success] = true;
     $color[r] = $red;
     $color[g] = $green;
     $color[b] = $blue;
     return $color;
   } else {
     $color[success] = false;
     $color[error] = "unable to convert hex to dec";
   };
 }
 function strip_chars($string, $char){
   $len = strlen($string);
   $count = count($char);
   if ($count >= 2) {
     for ($i=0;$i<=$count;$i++) {
       if ($char[$i]) {
         $found = stristr($string,$char[$i]);
         if ($found) {
           $val = substr($string,$found+1,$len-1);
           $string = $val;
         };
       };
     };
   } else {
     $found = stristr($string,$char);
     if ($found) {
       $val = substr($string,$found+1,$len-1);
     };
   };
   echo $val;
   return $val;
 }
 /*
   To use simply use the following function call:
     $color = convert_color("#FF");
     this will return the following assoc array if successful:
     *[success] = true
     *[r] = 255
     *[g] = 0
     *[b] = 0
     or copy and paste the following code:
     
     $hex = "FFFFFF"; // Color White
     $color = convert_color($hex);
     var_dump($color);
*/
?>
As you can see, the function "convert_color" accepts a hex # in most acceptable formats and returns an associative array.  [success] is set to TRUE if the function succeeds and FALSE if not.  The array members [r], [g] and [b] hold the red,green and blue values respectively.  If it fails, [error] holds a custom error message.
"strip_chars" is a support function written to remove the unwanted characters from the hex string, and sends the concatenated string back to the calling function.  It will accept either a single value or an array of values for the characters to remove.


djneoform

since i couldn't find one, here's an HEX to ASCII converter..
(takes HEX strings (in ASCII) and converts each two digit HEX code into it's ASCII equivalent)
function hex2ascii($str)
{
$p = '';
for ($i=0; $i < strlen($str); $i=$i+2)
{
$p .= chr(hexdec(substr($str, $i, 2)));
}
return $p;
}


halit yesil mail

RGB to Hex
Hex to RGB
Function
<?PHP
function rgb2hex2rgb($c){
if(!$c) return false;
$c = trim($c);
$out = false;
if(eregi("^[0-9ABCDEFabcdef\#]+$", $c)){
$c = str_replace('#','', $c);
$l = strlen($c);
if($l == 3){
unset($out);
$out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,1));
$out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 1,1));
$out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 2,1));
}elseif($l == 6){
unset($out);
$out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,2));
$out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 2,2));
$out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 4,2));
}else $out = false;

}elseif (eregi("^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$", $c)){
if(eregi(",", $c))
$e = explode(",",$c);
else if(eregi(" ", $c))
$e = explode(" ",$c);
else if(eregi(".", $c))
$e = explode(".",$c);
else return false;

if(count($e) != 3) return false;

$out = '#';
for($i = 0; $i<3; $i++)
$e[$i] = dechex(($e[$i] <= 0)?0:(($e[$i] >= 255)?255:$e[$i]));

for($i = 0; $i<3; $i++)
$out .= ((strlen($e[$i]) < 2)?'0':'').$e[$i];

$out = strtoupper($out);
}else $out = false;

return $out;
}
echo '#FFFFFF => '.rgb2hex2rgb('#FFFFFF').'
';
echo '#FFCCEE => '.rgb2hex2rgb('#FFCCEE').'
';
echo 'CC22FF => '.rgb2hex2rgb('CC22FF').'
';
echo '0 65 255 => '.rgb2hex2rgb('0 65 255').'
';
echo '255.150.3 => '.rgb2hex2rgb('255.150.3').'
';
echo '100,100,250 => '.rgb2hex2rgb('100,100,250').'
';
?>
Output
#FFFFFF =>
Array{
  red=>255,
  green=>255,
  blue=>255,
  r=>255,
  g=>255,
  b=>255,
  0=>255,
  1=>255,
  2=>255
}

#FFCCEE =>
Array{
  red=>255,
  green=>204,
  blue=>238,
  r=>255,
  g=>204,
  b=>238,
  0=>255,
  1=>204,
  2=>238
}
CC22FF =>
Array{
  red=>204,
  green=>34,
  blue=>255,
  r=>204,
  g=>34,
  b=>255,
  0=>204,
  1=>34,
  2=>255
}
0 65 255 => #0041FF
255.150.3 => #FF9603
100,100,250 => #6464FA


venk

Reply To Halit Yesil's script:
Great Function!! But, there's a problem with your script if the user passes something with three letters/numbers (eg/ #000).  You need to use str_repeat to duplicate each character.
               if($l == 3){
                   unset($out);
                   $out[0] = $out['r'] = $out['red'] = hexdec(str_repeat(substr($c, 0,1),2));
                   $out[1] = $out['g'] = $out['green'] = hexdec(str_repeat(substr($c, 1,1),2));
                   $out[2] = $out['b'] = $out['blue'] = hexdec(str_repeat(substr($c, 2,1),2));
               }


groobo

It's just a revision to marfastic's ligten_up script, it simply adds/subtracts mod_color to orig_color.
I use it often to adjust tonals rather than brightness only
<?
function mod_color($orig_color, $mod, $mod_color){
/*
$orig_color - original html color, hex
$mod_color - modifying color, hex
$mod - modifier '+' or '-'
usage: mod_color('CCCCCC', '+', '000033')
*/
// does quick validation
preg_match("/([0-9]|[A-F]){6}/i",$orig_color,$orig_arr);
preg_match("/([0-9]|[A-F]){6}/i",$mod_color,$mod_arr);
if ($orig_arr[0] && $mod_arr[0]) {
for ($i=0; $i<6; $i=$i+2) {
$orig_x = substr($orig_arr[0],$i,2);
$mod_x = substr($mod_arr[0],$i,2);
if ($mod == '+') { $new_x = hexdec($orig_x) + hexdec($mod_x); }
else { $new_x = hexdec($orig_x) - hexdec($mod_x); }
if ($new_x < 0) { $new_x = 0; }
else if ($new_x > 255) { $new_x = 255; };
$new_x = dechex($new_x);
$ret .= $new_x;
}
return $ret;
} else { return false; }
}
?>


19-jan-2005 05:33

I wondered long time what is the best way to generate RGB-color from HEX-color, and just now i found the simpliest way!
<?php
$hex = "FF00FF";
$rgb = hexdec($hex); // 16711935
?>
I hope this will save your time! :)


09-oct-2005 06:53

I needed to get the opposite colors so my website would be soft on the eyes.
<?php
function OppositeHex($color)
{
$r = dechex(255 - hexdec(substr($color,0,2)));
$r = (strlen($r) > 1) ? $r : '0'.$r;
$g = dechex(255 - hexdec(substr($color,2,2)));
$g = (strlen($g) > 1) ? $g : '0'.$g;
$b = dechex(255 - hexdec(substr($color,4,2)));
$b = (strlen($b) > 1) ? $b : '0'.$b;
return $r.$g.$b;
}
//Example
$color = '000000';
echo 'The opposite of #'.$color.' is #'.OppositeHex($color).';
?>


detrate

I made this for a little phpbb mod.  It was used to take the hex value from the database and make a color 20 (in decimal) less, resulting a darker color.
EXAMPLE: #336699 to #1f5285
<?php
$row1 = "336699"; // color
$c = 20;          // difference value
$rgb = array(substr($row1,0,2), substr($row1,2,2), substr($row1,4,2));
for($i=0; $i < 3; $i++)
{
 if((hexdec($rgb[$i])-$c) >= 0)
 {
  $rgb[$i] = hexdec($rgb[$i])-$c;
  $rgb[$i] = dechex($rgb[$i]);
   if(hexdec($rgb[0]) <= 9)
    $rgb[$i] = "0".$rgb[$i];
 } else {
   $rgb[$i] = "00";
 }
}
$row2 = $rgb[0].$rgb[1].$rgb[2];
?>


joey morwick

I found it helpful to have the inverse / reverse of this function laying around, since I wanted to insert some binary data into an xmlrpc call (it currently craps out when you do that), and I couldn't find one laying around, so here's a simple little function to do that:
function hex2bin($str) {
$build = '';
while(strlen($str) > 1) {
$build .= chr(hexdec(substr($str, 0, 2)));
$str = substr($str, 2, strlen($str)-2);
}
return $build;
}


chrism

hexdec from 4.1.0 onwards does not show
the same size limitation and therefore
works differently with large numbers than previous php versions.
To obtain the same results, use:
(int) hexdec (...)


greatwhitepine

Hex to binary conversion that works for large and small hex numbers.
<?php
function hexbin($str_hex) {
 $str_bin = FALSE;
 for ($i=0; $i < strlen($str_hex); $i++) {
   $str_bin .= sprintf("%04s", decbin(hexdec($str_hex[$i])));
 }
 return $str_bin;
}
$str_hex = "effffff20df";
print "\n           HEX VALUE: $str_hex\n";
printf("   REAL BINARY VALUE: %50s\n", hexbin($str_hex));
printf("CHOPPED BINARY VALUE: %50s\n\n", decbin(hexdec($str_hex)));
?>


andreas.schmeiler

Here's another hex2bin variant, works pretty well to me.
function hex2bin($hexdata) {
 
  for ($i=0;$i<strlen($hexdata);$i+=2) {
     $bindata.=chr(hexdec(substr($hexdata,$i,2)));
  }
 
  return $bindata;
}


cgarvis

Here is my version of hex2rgb for web colors to 24bit colors.
<?php
function hex2rgb_webcolors($hex) {
$hex = eregi_replace("[^a-fA-F0-9]", "", $hex);
switch( strlen($hex) ) {
case 2:
$hex = substr($hex,0,2)."0000";
break;
case 3:
$hex = substr($hex,0,1).substr($hex,0,1)
.substr($hex,1,1).substr($hex,1,1)
.substr($hex,2,1).substr($hex,2,1);
break;
case 4:
$hex = substr($hex,0,4)."00";
break;
case 6:
break;
default:
$hex = 0;
break;
}
return hexdec($hex);
}
?>


marfastic

Here is a function to brighten up any color:
function lighten_up($orig_color, $fraction_denom){
// return the color between the color and white
// based on the fraction denom that is passed

if(!isset($fraction_denom))
$fraction_denom = 2;
$highest_val = hexdec("FF");
$r = hexdec(substr($orig_color,0,2));
$r = ($highest_val-$r)/$fraction_denom + $r;
$g = hexdec(substr($orig_color,2,2));
$g = ($highest_val-$g)/$fraction_denom + $g;
$b = hexdec(substr($orig_color,4,2));
$b = ($highest_val-$b)/$fraction_denom + $b;
return dechex($r) . dechex($g) . dechex($b);
}


joe

Here is a fast block of code to convert HTML Style HEX colors to RGB:
--------------------
$r = hexdec(substr($color, 0, 2));
$g = hexdec(substr($color, 2, 2));
$b = hexdec(substr($color, 4, 2));
--------------------
hope it helps you, enjoy.


henrique

Function to convert a string with hexadecimal colors to an associative array with RGB values:
<?
function hex2dec($hex) {
 $color = str_replace('#', '', $hex);
 $ret = array(
   'r' => hexdec(substr($color, 0, 2)),
   'g' => hexdec(substr($color, 2, 2)),
   'b' => hexdec(substr($color, 4, 2))
 );
 return $ret;
}
/*** Example:
print_r(hex2dec('3D58BE'));
or
print_r(hex2dec('#3D58BE'));
will return
Array
(
 [r] => 61
 [g] => 88
 [b] => 190
)
***/
?>
Thanks !
Henrique Recidive


lukasz zajonc zajaczkowski

Function converting HEX to signed DEC
function hex2sdec ($hex)
{
 //how many bytes
 $ib = strlen ($hex) - (strlen ($hex) % $hex)) / $hex;
 if ((strlen ($hex) % 2) > 0)
   $ib = $ib + 1;
 //how many bites
 $ibb = 8 * $ib;
 //search for -1 value (max_uj)
 $buf = '1';
 for ($i = 1; $i <= $ibb - 1; $i++)
 {
   $buf .= '0';
 }
 $max_uj = bindec ($buf);
 //decide a sign, and calculate a value
 if (hexdec ($hex) < $max_uj)
 //+
 {
   $sdec = hexdec ($hex);
 }
 else
 //-
 {
   //search for max value + 1
   //(for ex. if hex = 23ef then max_p1 = ffff + 1)
   $buf = '';
   for ($i = 1; $i <= $ib; $i++)
   {
     $buf .= 'ff';
   }
   $max_p1 = hexdec ($buf) + 1;
   $sdec = hexdec ($hex) - $max_p1;
 }
 return $sdec;
}


repley

From color to color to ...... to color with fade effect. Good for dynamic bar chart.
<?php
//MultiColorFade(array hex-colors, int steps)
function MultiColorFade($hex_array, $steps) {
$tot = count($hex_array);
$gradient = array();
$fixend = 2;
$passages = $tot-1;
$stepsforpassage = floor($steps/$passages);
$stepsremain = $steps - ($stepsforpassage*$passages);
  for($pointer = 0; $pointer < $tot-1 ; $pointer++) {

      $hexstart = $hex_array[$pointer];
      $hexend = $hex_array[$pointer + 1];
      if($stepsremain > 0){
          if($stepsremain--){
              $stepsforthis = $stepsforpassage + 1;
          }
      }else{
          $stepsforthis = $stepsforpassage;
      }
   
      if($pointer > 0){
          $fixend = 1;        
      }
   
      $start['r'] = hexdec(substr($hexstart, 0, 2));
      $start['g'] = hexdec(substr($hexstart, 2, 2));
      $start['b'] = hexdec(substr($hexstart, 4, 2));
      $end['r'] = hexdec(substr($hexend, 0, 2));
      $end['g'] = hexdec(substr($hexend, 2, 2));
      $end['b'] = hexdec(substr($hexend, 4, 2));

      $step['r'] = ($start['r'] - $end['r']) / ($stepsforthis);
      $step['g'] = ($start['g'] - $end['g']) / ($stepsforthis);
      $step['b'] = ($start['b'] - $end['b']) / ($stepsforthis);
   
      for($i = 0; $i <= $stepsforthis-$fixend; $i++) {

          $rgb['r'] = floor($start['r'] - ($step['r'] * $i));
          $rgb['g'] = floor($start['g'] - ($step['g'] * $i));
          $rgb['b'] = floor($start['b'] - ($step['b'] * $i));

          $hex['r'] = sprintf('%02x', ($rgb['r']));
          $hex['g'] = sprintf('%02x', ($rgb['g']));
          $hex['b'] = sprintf('%02x', ($rgb['b']));
 
          $gradient[] = strtoupper(implode(NULL, $hex));
      }
  }

  $gradient[] = $hex_array[$tot-1];

return $gradient;
}
//end MultiColorFade()
//start test
$multi_hex_array = array();
$multi_hex_array[] = array('FF0000','FFFF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000','FFFFFF');
foreach($multi_hex_array as $hex_array){
  $totcolors = count($hex_array);
  $steps = 44;
  $a = MultiColorFade($hex_array, $steps);
  $tot = count($a);
  $table = '<table border=1 width="300">' . "\n";
  for ($i = 0; $i < $tot; $i++){
      $table .= ' <tr><td bgcolor="' . $a[$i] . '">' . ($i+1) .'</td><td><pre>' . $a[$i] . '</pre></td></tr>' . "\n";
  }

  $table .= '</table><br /><br />';

  echo '<br />Demanded steps = ' . $steps . '<br />';
  echo 'Returned steps = ' . $tot;

  if($steps == $tot){
      echo '<br />OK.' . $steps . ' = ' . $tot . '<br />';
  }else{
      echo '<br /><span style="color:#FF0000">FAILED! Demanded steps and returned steps are NOT equal!: ' . $steps . ' != ' . $tot . '</span><br />';
  }
  echo $table;

}
//end test
?>
Repley.


ayadav

From Amit Yadav
Hex to binary conversion
$num = hexdec("20DF");
echo binfromdec($num);
function binfromdec($num)
{
if ($num > 32766) return ("Too Large!");
if ($num & 16384) $bit15 = 1;
if ($num & 8192) $bit14 = 1;
if ($num & 4096) $bit13 = 1;
if ($num & 2048) $bit12 = 1;
if ($num & 1024) $bit11 = 1;
if ($num & 512) $bit10 = 1;
if ($num & 256) $bit9 = 1;
if ($num & 128) $bit8 = 1;
if ($num & 64) $bit7 = 1;
if ($num & 32) $bit6 = 1;
if ($num & 16) $bit5 = 1;
if ($num & 8) $bit4 = 1;
if ($num & 4) $bit3 = 1;
if ($num & 2) $bit2 = 1;
if ($num & 1) $bit1 = 1;
return ("" . $bit15 . $bit14 . $bit13 . $bit12 . $bit11 . $bit10 . $bit9 . $bit8 . $bit7 . $bit6 . $bit5 . $bit4 . $bit3 . $bit2 . $bit1);
}


andychase

For hex numbers larger than 7FFFFFFF (E.G. PalmOS dates in seconds elapsed since 01/01/1904), I came up with this:
function bighexdec($hexnumber){
$numlength = strlen($hexnumber);
$decnumber = 0;
for($x = 1; $x <= $numlength; $x++){
$place = $numlength - $x;

$operand = hexdec(substr($hexnumber,$place,1));

$exponent = pow(16,$x-1);
$decValue = $operand * $exponent;

$decnumber += $decValue;
}
return $decnumber;

}


_meto alt+q web.de

Damn, this took me some real long time! Maybe it's helpfull for those who even have no idea of color-Schemes like me ;)
If u want to generate PDF's for Print Offices u need to set all the colors in CMYK.
Here is a Function that will convert RGB to CMYK
<?
function hex2rgb($hex) {
 $color = str_replace('#','',$hex);
 $rgb = array('r' => hexdec(substr($color,0,2)),
              'g' => hexdec(substr($color,2,2)),
              'b' => hexdec(substr($color,4,2)));
 return $rgb;
}
function rgb2cmyk($var1,$g=0,$b=0) {
  if(is_array($var1)) {
     $r = $var1['r'];
     $g = $var1['g'];
     $b = $var1['b'];
  }
  else $r=$var1;
  $cyan    = 255 - $r;
  $magenta = 255 - $g;
  $yellow  = 255 - $b;
  $black   = min($cyan, $magenta, $yellow);
  $cyan    = @(($cyan    - $black) / (255 - $black)) * 255;
  $magenta = @(($magenta - $black) / (255 - $black)) * 255;
  $yellow  = @(($yellow  - $black) / (255 - $black)) * 255;
  return array('c' => $cyan / 255,
               'm' => $magenta / 255,
               'y' => $yellow / 255,
               'k' => $black / 255);
}
$color=rgb2cmyk(hex2rgb('#FF0000'));
pdf_setcolor($pdf, "both", "cmyk", $color['c'], $color['m'], $color['y'], $color['k']);
?>
U can call it with parameters (r,g,b) or just with an array(r,g,b) that contains these values.
Hope it works correct. All testing was fine.


bishop

Bullet-proof hex-to-rgb colour converter like brian at sagesport dot com wanted, just far fewer code lines. As a bonus, gives you the ability to return as string or array:
<?php
   function &hex2rgb($hex, $asString = true)
   {
       // strip off any leading #
       if (0 === strpos($hex, '#')) {
           $hex = substr($hex, 1);
       } else if (0 === strpos($hex, '&H')) {
           $hex = substr($hex, 2);
       }      
       // break into hex 3-tuple
       $cutpoint = ceil(strlen($hex) / 2)-1;
       $rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);
       // convert each tuple to decimal
       $rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
       $rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
       $rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);
       return ($asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
   }
?>
Handles 2, 3, and 6 character colour codes with leading # or &H.


gelado

Another hex to decimal converter, up to the precision of PHP floats.
function longhex($hex)
{
$dec = 0;
$bitval = 1;
for($pos = 1; $pos <= strlen($hex); $pos++) {
$dec += hexdec(substr($hex, -$pos, 1)) * $bitval;
$bitval *= 16;
}
return($dec);
}


gabriel reguly

After esnhexdec from "rledger at gmail dot com",  the esndechex:
<?php
function esndechex($dec){
$a = strtoupper(dechex(substr($dec, 1,  2)));
$b = strtoupper(dechex(substr($dec, 3, 10)));
return $a . $b;
}
?>


cory

A handy little function to convert HEX colour codes to "web safe" colours...
<?php
function color_mkwebsafe ( $in )
{
  // put values into an easy-to-use array
  $vals['r'] = hexdec( substr($in, 0, 2) );
  $vals['g'] = hexdec( substr($in, 2, 2) );
  $vals['b'] = hexdec( substr($in, 4, 2) );
  // loop through
  foreach( $vals as $val )
  {
      // convert value
      $val = ( round($val/51) * 51 );
      // convert to HEX
      $out .= str_pad(dechex($val), 2, '0', STR_PAD_LEFT);
  }
  return $out;
}
?>
Example: color_mkwebsafe('0e5c94');
Produces: 006699
Hope this helps someone out... Happy coding. :-)


k10206

<?
function hexrgb($hexstr) {
   $int = hexdec($hexstr);
   return array("red" => 0xFF & ($int >> 0x10), "green" => 0xFF & ($int >> 0x8), "blue" => 0xFF & $int);
}
?>


Change Language


Follow Navioo On Twitter
abs
acos
acosh
asin
asinh
atan2
atan
atanh
base_convert
bindec
ceil
cos
cosh
decbin
dechex
decoct
deg2rad
exp
expm1
floor
fmod
getrandmax
hexdec
hypot
is_finite
is_infinite
is_nan
lcg_value
log10
log1p
log
max
min
mt_getrandmax
mt_rand
mt_srand
octdec
pi
pow
rad2deg
rand
round
sin
sinh
sqrt
srand
tan
tanh
eXTReMe Tracker