Saturday, August 13, 2011

PHP code for rendering a 'barrel widget' for charting and graphing.

I had call to write a PHP based barrel widget the other day and through I'd share the process.
The end-result needed to look like this: 
 
In order to achieve this, I chopped the graphic into the following PNG files:






Then the code which made it render as a complete new 'barrell chart' or 'barrell widget' looked like this:

<?php
function graph_render_barrel($val,$name){
    //$val is the percent value passed to the function, and $name is the name of the file to be saved
    $filename=$name;
    $img = imagecreatefrompng("g_barrel.png");
    imagealphablending($img, true);
    imagesavealpha($img, true);
    $greenbase = imagecreatefrompng("g_barrel_breen_bot.png");
    imagealphablending($greenbase, true);
    imagesavealpha($greenbase, true);
    $greenmid = imagecreatefrompng("g_barrel_breen_bak.png");
    imagealphablending($greenmid, true);
    imagesavealpha($greenmid, true);
    $greentop = imagecreatefrompng("g_barrel_breen_top.png");
    imagealphablending($greentop, true);
    imagesavealpha($greentop, true);
    $stretch=floor(184*($val/100)); //0 to 184
    imagecopyresampled($img, $greenbase, 2, 211, 0, 0, 143,21, 143,21);
    imagecopyresampled($img, $greenmid, 2, (211-$stretch), 0, 0, 143,(20+($stretch-20)), 143,20);
    imagecopyresampled($img, $greentop, 2, ((211-$stretch)-22), 0, 0, 143,45, 143,45);
    imagepng ( $img , "portal/saasmsallstar/UserFiles/bb_crp_graph_images/$filename" , 0 ,  PNG_ALL_FILTERS);
    imagedestroy($img);
    return($name); //handle possible retuns here
}
?>

So, in practice it could be used like this:

<?php
echo("<img src=\"".graph_render_barrel(66,"path/to/new_graphic.png")."\" >");
?>

No comments:

Post a Comment