Several month’s ago, I wrote a small PHP script to generate an image representing a countdown clock. The image was static and was sufficient enough to meet my demands, knowing that refreshing the page would request a new image showing an updated time remaining clock.
I used this image on this forum in my signature and it was a hit with the community. However, the script went to the next level when I was asked, “why doesn’t it count down? I always have to refresh.”
As a programmer, I set a goal to do something simple. Obviously using PHP GD is simple enough, but I hadn’t even thought to animate the image. This is overkill for a vBulletin signature and normally I’d solve this problem of a countdown with some javascript, but more often than not, you can’t do that kind of stuff in a signature. The only way to fake it is to animate an image.
Also, I learned a lesson in judging audience. It doesn’t matter how simple the code is, or how proud you are of that simplicity; if it doesn’t look cool, they don’t care.
The PHP script that generates an animated image is pretty simple and straight forward. The class I’m using is GIFEncoder written by László Zsidi. I believe I found it on PHP Classes, an insufferable website to say the least.
To animate an image, you first need to generate the frames to be animated. In the case of the countdown, each frame is held for 1 second for a total of 120 seconds before looping. This will sufficiently fake a 2-minute countdown, more than enough for the typical forum goer.
Each image needs to be generated and captured to some sort of buffer in PHP. The only way to capture image output in PHP with GD is using the OB functions.
After generating all the images, your GIFEncoder class can go to work. It can be a bit tricky to understand at first, however with my demonstration, it should be self explanatory.
Basically, you’re going to do this:
Here’s a GIST of my demonstration. Here’s a GIST of GIFEncoder class, since it seems to have gone bye-bye. Here’s what your animated GIF can look like.