Archive for the ‘’ Category

making a radar loop with PHP

Sunday, September 3rd, 2006

So a few days ago I was out with friends and a storm was on it’s way in. Naturally, I’m the one they ask whether it’s ‘about to hit us’, so I pull up the web browser on my Treo 650 and realize… um… there’s no quick way to pull up a radar loop. I mean, I used the great mobile site from the NWS, but it still didn’t give me the effect I wanted. And hey, I’m already filling a database with weather observations and radar images! So I decided to see what it would take to make a custom radar loop that I could get to at any given moment. The Treo can display animated gif files, so that seemed like the most efficient solution. The question is, how do we create an animated gif using PHP?

Well, I don’t like to reinvent the wheel, especially if someone else out there has made a wheel superior to one that I could make myself. :) Hence, I found this. From here, we just need to read in the images and feed them to the GifMerge class.

Header(‘Content-type: image/gif’);

$count = 1;
$q = mysql_query(‘select * from (select recorded, radar from weather order by recorded desc limit 10) as t order by recorded’);
while($r = mysql_fetch_array($q)){
$image_p = imagecreate(300, 300);
$image = imagecreatefromgif(“radar/”.substr($r[‘radar’], 35));
imagecopyresampled($image_p, $image, 0, 0, 210, 120, 300, 300, 300, 300);
imagegif($image_p, “radar/loop/frame”.$count.”.gif”);

$__i = array(“radar/loop/frame1.gif”, “radar/loop/frame2.gif”, “radar/loop/frame3.gif”, “radar/loop/frame4.gif”, “radar/loop/frame5.gif”, “radar/loop/frame6.gif”, “radar/loop/frame7.gif”, “radar/loop/frame8.gif”, “radar/loop/frame9.gif”, “radar/loop/frame10.gif”);
$__d = array(30, 30, 30, 30, 30, 30, 30, 30, 30, 300);
$gifmerge = new GifMerge($__i, 1, 1, 1, -10, $__d, 2, 0, 0, ‘C_FILE’);
echo $gifmerge -> getAnimation();

One issue I had was that the images I scrape are rather large, and when you merge 10 of them into an animated GIF, you end up with an image that a little bigger than most handheld devices like to deal with. Not to mention, we’re talking about a GPRS connection here… it would be easier to download 50kb than 500kb. So to get around that, I used the imagecopyresampled function to cut out the portion of the image most important to me. I then save the cropped image into a ‘loop’ directory as 10 separate ‘frame’ files. After that, it’s pretty straightforward to follow the GifMerge example to create the image.

So without further ado, here’s the result: