Skip to content

Instantly share code, notes, and snippets.

@bgadrian
Created March 16, 2015 17:29
Show Gist options
  • Save bgadrian/bd9a4ed4cdb2e29b84c0 to your computer and use it in GitHub Desktop.
Save bgadrian/bd9a4ed4cdb2e29b84c0 to your computer and use it in GitHub Desktop.
Generate a color palette between two colors. Returns hex css codes.
<?php
/** Thanks to http://www.herethere.net/~samson/php/color_gradient/
Usage :
* print_r(_generateGradients('000000','FFFFFF',16));creates 16 nuances between white and black, returns hex css
print_r(_generateGradients('#FF0000','#800080'));
*/
function _generateGradientsInterpolate($pBegin, $pEnd, $pStep, $pMax) {
if ($pBegin < $pEnd) {
return (($pEnd - $pBegin) * ($pStep / $pMax)) + $pBegin;
} else {
return (($pBegin - $pEnd) * (1 - ($pStep / $pMax))) + $pEnd;
}
}
function _generateGradients($theColorBegin=0x000000,$theColorEnd=0xffffff,$theNumSteps=10)
{
//transform to hex, and get rid of # if exists
$theColorBegin = hexdec(str_replace('#','',$theColorBegin));
$theColorEnd = hexdec(str_replace('#','',$theColorEnd));
//failsafe color codes
$theColorBegin = (($theColorBegin >= 0x000000) && ($theColorBegin <= 0xffffff)) ? $theColorBegin : 0x000000;
$theColorEnd = (($theColorEnd >= 0x000000) && ($theColorEnd <= 0xffffff)) ? $theColorEnd : 0xffffff;
$theNumSteps = (($theNumSteps > 0) && ($theNumSteps < 256)) ? $theNumSteps : 16;
$theR0 = ($theColorBegin & 0xff0000) >> 16;
$theG0 = ($theColorBegin & 0x00ff00) >> 8;
$theB0 = ($theColorBegin & 0x0000ff) >> 0;
$theR1 = ($theColorEnd & 0xff0000) >> 16;
$theG1 = ($theColorEnd & 0x00ff00) >> 8;
$theB1 = ($theColorEnd & 0x0000ff) >> 0;
$result = array();
for ($i = 0; $i <= $theNumSteps; $i++) {
$theR = $this->_generateGradientsInterpolate($theR0, $theR1, $i, $theNumSteps);
$theG = $this->_generateGradientsInterpolate($theG0, $theG1, $i, $theNumSteps);
$theB = $this->_generateGradientsInterpolate($theB0, $theB1, $i, $theNumSteps);
$theVal = ((($theR << 8) | $theG) << 8) | $theB;
$result[] = sprintf("#%06X",$theVal);//strtoupper(str_pad(dechex($theVal),6,'0'))
}
return $result;
}//end _generateGradients
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment