Make an animated GIF with PHP's ImageMagick AP

2019-01-23 09:02发布

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.

1条回答
再贱就再见
2楼-- · 2019-01-23 09:43

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.

查看更多
登录 后发表回答