Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an animated GIF with PHP's ImageMagick API

I can do it easily in my OS

convert -delay 1/1 -loop 0 *.gif animated.gif

But I can't find how to do this in the PHP API. No resizing or anything needed, I've just got a set of frames that need animating.

like image 675
joedborg Avatar asked Feb 23 '12 17:02

joedborg


1 Answers

While I'm not a PHP expert, I know that this issue isn't a too difficult one. What you want to do is create an Imagick object that you can append your frames to. With each frame you can change parameters like timing etc.

Assuming you're working with images that are uploaded from a basic web form, I've written a basic example that loops through images that were uploaded with a name of "image0", where "0" goes up to however many files are included. You could naturally just add images by using the same methods on fixed file names or whatever.

$GIF = new Imagick();
$GIF->setFormat("gif");

for ($i = 0; $i < sizeof($_FILES); ++$i) {
    $frame = new Imagick();
    $frame->readImage($_FILES["image$i"]["tmp_name"]);
    $frame->setImageDelay(10);
    $GIF->addImage($frame);
}

header("Content-Type: image/gif");
echo $GIF->getImagesBlob();

This example creates an Imagick object that is what will become our GIF. The files that were uploaded to the server are then looped through and each one is firstly read (remember however that this technique relies on that the images are named as I described above), secondly it gets a delay value, and thirdly, it's appended to the GIF-to-be. That's the basic idea, and it will produce what you're after (I hope).

But there's lot to tamper with, and your configuration may look different. I always found the php.net Imagick API reference to kind of suck, but it's still nice to have and I use it every now and then to reference things from the standard ImageMagick.

Hope this somewhat matches what you were after.

like image 191
fredrikekelund Avatar answered Sep 23 '22 05:09

fredrikekelund