Skip to content

Instantly share code, notes, and snippets.

@miku
Forked from avioli/gif to mp4.sh
Created May 30, 2018 20:09
Show Gist options
  • Save miku/fc90e97a4d17ba53d8b8ec8de300ac10 to your computer and use it in GitHub Desktop.
Save miku/fc90e97a4d17ba53d8b8ec8de300ac10 to your computer and use it in GitHub Desktop.
#!/bin/bash
# requires imagemagick and ffmpeg (tested with latest versions)
# make sure you set an INFILE variableo first
INFILE=$1
# get GIF info
video=$(ffmpeg -i "$INFILE" 2>&1 /dev/null | grep "Video:");
# get GIF Frames per second
fps=$(echo "$video" | sed -n "s/.* \([0-9.]*\) fps.*/\1/p");
# a convinience variable so we can easily set FPS on the video
fps1000=$(echo "scale=0;$fps*100000/100" | bc);
# extract the frames in sequental PNGs
convert -coalesce "$INFILE" temp%d.png;
# sequence the PNGs into an MP4 container (libx264 encoded by default)
ffmpeg -y -f image2 -r "$fps1000/1000" -i temp%d.png -v:b 1500 -an -vf scale="'if(eq(mod(iw,2),0),iw,iw-1)':'if(eq(mod(ih,2),0),ih,ih-1)'" "$INFILE.mp4"
# remove the temporary PNGs
rm temp*.png;
# notes:
# fps detection is not thoroughly tested, thus not reliable; one could read the GIF and calculate each frame's delay (would allow variable frame rate GIF detection as well)
# "convert -coalesce" makes disposable GIFs to export as full frames
# "ffmpeg ... -vf scale=..." ensures MP4 output dimensions is divisable by 2 (a rather unoptimized calculation)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment