PHP Tutorial: Mixing HEX Colors within a Range

Leave a comment Standard

This seems to be coming up more often with the client games I’ve been working on. Now everyone wants  dynamic images and colors. This function will produce a random hexcode color within the range of the two hexcode colors given. It’s inclusive so you can also get the original colors returned.

<?php
/**
* Purpose: produce a color within a range of two hexcode colors
* Precondition: two hexcode colors, min/max range values optional
* Postcondition: one random color within the range returned
**/
function mixRange($color1, $color2, $MIN = 1, $MAX = 10)
{
    $range = rand($MIN, $MAX);
 
    $r = hexdec(substr($color1,0,2));
    $g = hexdec(substr($color1,2,2));
    $b = hexdec(substr($color1,4,2));
     
    $gr = (hexdec(substr($color2,0,2))-$r)/$MAX; //Graduation Size Red
    $gg = (hexdec(substr($color2,2,2))-$g)/$MAX;
    $gb = (hexdec(substr($color2,4,2))-$b)/$MAX;
     
    return str_pad(dechex($r+($gr*$range)),2,'0',STR_PAD_LEFT) .
        str_pad(dechex($g+($gg*$range)),2,'0',STR_PAD_LEFT) .
        str_pad(dechex($b+($gb*$range)),2,'0',STR_PAD_LEFT);
}
?>
Advertisements