PHP Heatmap Gradient Color Generator

December 25th, 2011

Based on the awesome work done here Samson PHP Color Gradient Generator, I have packed up his code into two functions that are by default set to generate heatmap blue to red color gradients, in as many steps as you need.

https://gist.github.com/bendauphinee/10472641

function heatSteps($config){
    $config['colorStart'] = (isset($config['colorStart'])) ? hexdec($config['colorStart']) : 0xdee7f8;
    $config['colorEnd'] = (isset($config['colorEnd'])) ? hexdec($config['colorEnd']) : 0xff0f15;
    $config['colorSteps'] = (isset($config['colorSteps'])) ? $config['colorSteps'] : 10;

    $config['colorStart'] = (($config['colorStart'] >= 0x000000) && ($config['colorStart'] <= 0xffffff)) ? $config['colorStart'] : 0x000000;
    $config['colorEnd'] = (($config['colorEnd'] >= 0x000000) && ($config['colorEnd'] <= 0xffffff)) ? $config['colorEnd'] : 0xffffff;
    $config['colorSteps'] = (($config['colorSteps'] > 0) && ($config['colorSteps'] < 256)) ? $config['colorSteps'] : 256;

    $theR0 = ($config['colorStart'] & 0xff0000) >> 16;
    $theG0 = ($config['colorStart'] & 0x00ff00) >> 8;
    $theB0 = ($config['colorStart'] & 0x0000ff) >> 0;

    $theR1 = ($config['colorEnd'] & 0xff0000) >> 16;
    $theG1 = ($config['colorEnd'] & 0x00ff00) >> 8;
    $theB1 = ($config['colorEnd'] & 0x0000ff) >> 0;

    $colorSteps = array();
    for($i = 0; $i <= $config['colorSteps']; $i++){
        $theR = interpolateHeatSteps($theR0, $theR1, $i, $config['colorSteps']);
        $theG = interpolateHeatSteps($theG0, $theG1, $i, $config['colorSteps']);
        $theB = interpolateHeatSteps($theB0, $theB1, $i, $config['colorSteps']);

        $colorSteps[] = dechex(((($theR << 8) | $theG) << 8) | $theB);
    }

    return($colorSteps);
}

function interpolateHeatSteps($pBegin, $pEnd, $pStep, $pMax){
    if ($pBegin < $pEnd){
        return(($pEnd - $pBegin) * ($pStep / $pMax)) + $pBegin;
    }else{
        return(($pBegin - $pEnd) * (1 - ($pStep / $pMax))) + $pEnd;
    }
}
WordPress - Entries (RSS) and Comments (RSS) - © 2011 Ben Dauphinee