Using ffmpeg, how can I convert an MP4, crop and resize to GIF


I would like ffmpeg to grab a 1280×720 MP4 video file, crop to square size ratio, resize it to 640×640

The following two commands work for me with great GIF quality bu it's just missing the correct resizing.
It does give me a GIF output but the size is 1138×640 instead of 640×640.

Generating a palette:

ffmpeg -y -ss 30 -t 3 -i input.mp4 \
-vf fps=10,scale=1138:-1:flags=lanczos,palettegen palette.png

Outputting GIF using the palette:

ffmpeg -ss 30 -t 3 -i input.mp4 -i palette.png -filter_complex \
"fps=10,scale=1138:-1:flags=lanczos[x];[x][1:v]paletteuse" output.gif

This gives me a 1138×640.gif but how can I get it to be 640×640 without relying on another separate command?

Best Answer

Here's a simple method that will work for 1280x720 inputs.

Generate palette:

ffmpeg -i input.mp4 -filter_complex "fps=10,scale=-1:640,crop=ih:ih,setsar=1,palettegen" palette.png

Create GIF:

ffmpeg -i input.mp4 -i palette.png -filter_complex "[0]fps=10,scale=-1:640,crop=ih:ih,setsar=1[x];[x][1:v]paletteuse" output.gif

You can make this more complex if desired by adding the force_aspect_ratio scale option to fit arbitrary input sizes into 640x640, and by adding split and fifo to avoid making the temporary palette file.