Imagick: Remove frames from an animated GIF?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 07:37:23

I've been going through the Imagick documentation for a while, and tried a couple of things... But I didn't manage to do what you want either -- so, we are at least two who can't find out a clean way ^^

Anyway, the only way I managed to remove a frame for an animated GIF image was by creating a new one, containing only the frames I didn't want to remove :-(


Considering I loaded an image this way :

// Load the existing image
$image = new Imagick(dirname(__FILE__) . '/animated-gif-source.gif');

(This is an animated gif, with 3 frames ; I want to "remove" the second one).


As I said, only way I found to "remove a frame" is this one :

$new_image = new Imagick();

$i = 1;
foreach ($image as $frame) {
    if ($i===1 || $i===3) {
        // 3 frames ; we keep the first and third one
        // ie, remove the second one
        $new_image->addImage($frame->getImage());
    }
    $i++;
}

So :

  • create a new image
  • iterate over the frames of the orignal one
  • if the current frame is one I want to keep, copy it to the new image


And, in the end, to output the image to the browser :

// To directly output to the browser
header('Content-Type: image/gif');
echo $new_image->getImagesBlob();

Or, to write it to a file :

// To write the new image to a file
// Must use writeImages, and not writeImage (multi-frames ! )
$new_image->writeImages(dirname(__FILE__) . '/animated-gif-output.gif', true);

Each one of these outputs only contain the first and third frames ; so, it's working...
But, as you said, it doesn't feel good :-(


It will probably work just fine for most images, I think ; you might encouter troubles with big images, but animated GIFs are generally not that big... are they ?


Other way might be using convert from the command line... But... not that great, and I didn't find a way to just remove a frame with those either :-(

I have only used the command line utilities for IM.

convert srcImage.gif[0] dstImage.gif

Should do the trick unless I forgot an option.

[0] referes to the first frame of the animated gif.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!