Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert a section of a YouTube video to an animated GIF
#!/bin/bash
# brew install x265
# brew install ffmpeg
# brew install youtube-dl
# brew install imagemagick
ID='U65_uY5N2WM' # YouTube video ID, i.e. https://www.youtube.com/watch?v={ID}
# fetch the video file with youtube-dl
# convert it to MP4 (not really needed, but keeps the filename predictable)
if [ ! -f $ID.mp4 ]; then
youtube-dl --output '%(id)s.%(ext)s' --recode-video mp4 $ID
fi
# convert the video file to GIF with ffmpeg
START='00:00:04.000' # start 4 seconds in
LENGTH='00:00:05.000' # end after 5 seconds
SIZE='400x300' # size of the output GIF
ffmpeg -ss $START -i $ID.mp4 -pix_fmt rgb8 -r 10 -s $SIZE -t $LENGTH $ID-unoptimized.gif
# optimize the GIF with imagemagick
convert -layers Optimize $ID-unoptimized.gif $ID.gif
# credits:
# http://www.commandlinefu.com/commands/view/10002/create-an-animated-gif-from-a-youtube-video
# http://superuser.com/a/436109/106809
@uniring

This comment has been minimized.

Copy link

@uniring uniring commented Mar 2, 2018

You can improve the performance a lot using this line:

ffmpeg -i $(youtube-dl -f 18 --get-url https://www.youtube.com/watch?v=$ID) -ss $START -t $LENGTH -c:v copy -c:a copy $ID.mp4

Instead of:

youtube-dl --output '%(id)s.%(ext)s' --recode-video mp4 $ID

And having defined START and LENGTH variables before this part.

This will avoid downloading and recoding the entire video. For a video of 4 minutes this reduced the time to make the gif from ~80sec to 6sec.

@itamarsky

This comment has been minimized.

Copy link

@itamarsky itamarsky commented Apr 27, 2018

  • Awesome gist: done
@betterfuturewe

This comment has been minimized.

Copy link

@betterfuturewe betterfuturewe commented Aug 27, 2019

I use Allavsoft to do that. Copy the video url to Allavsoft, check before Automatically Convert to to select GIF from animation option and click Download button.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment