How do I crop an animated gif using ImageMagick?

ImagemagickCropAnimated Gif

Imagemagick Problem Overview


There's plenty of information about cropping images, but attempting to crop (or trim) animations produces strange results. Sometimes they flicker, or come with extra frames, or some frames crop correctly and others become offset. How do I prevent all this from happening?

Imagemagick Solutions


Solution 1 - Imagemagick

convert input.gif -coalesce -repage 0x0 -crop WxH+X+Y +repage output.gif
  • Animated gifs are often optimised to save space, but imagemagick doesn't seem to consider this when applying the crop command and treats each frame individually. -coalesce rebuilds the full frames.
  • Other commands will take into consideration the offset information supplied in the original gif, so you need to force that to be reset with -repage 0x0.
  • The crop itself is straightforward, with width, height, x offset and y offset supplied respectively. For example, a crop 40 wide and 30 high at an x offset of 50 = 40x30+50+0.
  • Crop does not remove the canvas that it snipped from the image. Applying +repage after the crop will do this.

Solution 2 - Imagemagick

Even with the coalesce and repage, I could not get ImageMagick to crop and resize animated gifs very well.

I found a program called Gifsicle and it works great for manipulating animated gifs.

gifsicle --crop 0,0-100,100 --output out.gif in.gif

It can also do all sorts of other operations. Check it out!

Solution 3 - Imagemagick

Animations are often optimized, which means that some frames are smaller than others. So in ImageMagick you probably want to coalesce the animation before cropping.

convert in_animation.gif -coalesce -crop WxH+X+Y +repage -layers optimize out_animation.gif


You may need to add a -dispose method before reading the input animation to avoid a flicker. Also set the -delay and -loop at the end, if you want to make changes.

See

http://www.imagemagick.org/Usage/anim_basics/#dispose http://www.imagemagick.org/Usage/anim_basics/#coalesce http://www.imagemagick.org/script/command-line-options.php#layers

Solution 4 - Imagemagick

The following line worked with me on Mac

convert -dispose 2 input.gif -trim -layers TrimBounds animation.gif

Here is the source

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjimmetryView Question on Stackoverflow
Solution 1 - ImagemagickjimmetryView Answer on Stackoverflow
Solution 2 - ImagemagickfletchownsView Answer on Stackoverflow
Solution 3 - Imagemagickfmw42View Answer on Stackoverflow
Solution 4 - ImagemagickKernelView Answer on Stackoverflow