Generate GIF Image Using PHP

Since the 2015 Hurricane Season started, I have been downloading satellite images from the National Hurricane Center website and I wondered, “Was it possible to write a PHP script to convert all these images to an animated GIF?” The answer: YES!

I came across Jeroen van Wissen’s Website and his article was easy to follow and, the best part, the script worked. Here’s how I…he did it.

He used the GIFEncoder.class by László Zsidi on phpclasses.org. I modified his code a bit to get it to work to my liking and instead of using imagegif($image); in his code, I used imagejpeg($image); for mine.

Here is his demo code below:

header ('Content-type:image/gif');
include('GIFEncoder.class.php');
$text = "Hello World";

// Open the first source image and add the text.
$image = imagecreatefrompng('source01.png');
$text_color = imagecolorallocate($image, 200, 200, 200);
imagestring($image, 5, 5, 5, $text, $text_color);

// Generate GIF from the $image
// We want to put the binary GIF data into an array to be used later,
// so we use the output buffer.
ob_start();
imagegif($image);
$frames[]=ob_get_contents();
$framed[]=40;

// Delay in the animation.
ob_end_clean();

// And again..
// Open the first source image and add the text.
$image = imagecreatefrompng('source02.png');
$text_color = imagecolorallocate($image, 200, 200, 200);
imagestring($image, 5, 20, 20, $text, $text_color);

// Generate GIF from the $image
// We want to put the binary GIF data into an array to be used later,
// so we use the output buffer.
ob_start();
imagegif($image);
$frames[]=ob_get_contents();
$framed[]=40;

// Delay in the animation.
ob_end_clean();

// Generate the animated gif and output to screen.
$gif = new GIFEncoder($frames,$framed,0,2,0,0,0,'bin');
echo $gif->GetAnimation();

Tags: ,