Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I crop an animated gif using ImageMagick?

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?

like image 481
jimmetry Avatar asked Dec 26 '12 06:12

jimmetry


People also ask

How do you crop on ImageMagick?

To crop an image using ImageMagick, you need to specify the X and Y coordinates of the top corner of the crop rectangle and the width and height of the crop rectangle. Use the mogrify command if you want the images to be replaced in-place or use the convert command otherwise to make a copy.


2 Answers

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.
like image 127
jimmetry Avatar answered Sep 21 '22 02:09

jimmetry


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!

like image 26
fletchowns Avatar answered Sep 23 '22 02:09

fletchowns