PHP Tutorial: Mixing HEX Colors

<?php
/****************
* Purpose: mix two colors together
* Precondition: two colors in hex RGB format
* Postcondition: a single color returned that's the combo of the two
****************/
function mixcolors($color1, $color2)
{

  $c1_p1 = hexdec(substr($color1, 0, 2));
  $c1_p2 = hexdec(substr($color1, 2, 2));
  $c1_p3 = hexdec(substr($color1, 4, 2));

  $c2_p1 = hexdec(substr($color2, 0, 2));
  $c2_p2 = hexdec(substr($color2, 2, 2));
  $c2_p3 = hexdec(substr($color2, 4, 2));

  $m_p1 = sprintf('%02x', (round(($c1_p1 + $c2_p1)/2)));
  $m_p2 = sprintf('%02x', (round(($c1_p2 + $c2_p2)/2)));
  $m_p3 = sprintf('%02x', (round(($c1_p3 + $c2_p3)/2)));

 return    $m_p1 . $m_p2 . $m_p3;
}
?>

You may also like...

1 Response

  1. Avalon says:

    Seems to conver 0x numbers to just x

    Another option:

    function mixcolors($color1, $color2){

    $r1 = hexdec(substr($color1, 0, 2));
    $g1 = hexdec(substr($color1, 2, 2));
    $b1 = hexdec(substr($color1, 4, 2));

    $r2 = hexdec(substr($color2, 0, 2));
    $g2 = hexdec(substr($color2, 2, 2));
    $b2 = hexdec(substr($color2, 4, 2));

    $r3 = ceil(($r1 + $r2) / 2);
    $g3 = ceil(($g1 + $g2) / 2);
    $b3 = ceil(($b1 + $b2) / 2);

    $hex =””;
    $hex.= str_pad(dechex($r3), 2, “0”, STR_PAD_LEFT);
    $hex.= str_pad(dechex($g3), 2, “0”, STR_PAD_LEFT);
    $hex.= str_pad(dechex($b3), 2, “0”, STR_PAD_LEFT);

    return $hex;
    }

Leave a Reply