Last active
November 28, 2015 19:50
-
-
Save renaudcerrato/14af0fc855fda52e6587 to your computer and use it in GitHub Desktop.
Bash script to convert video to GIF.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
ensure_installed() { | |
command -v $1 >/dev/null 2>&1 || { echo -e >&2 "$1 not found.\nTry: sudo apt-get install $1.\nAborting."; exit 1; } | |
} | |
function usage() { | |
cat << EOF | |
$1 | |
Usage: $0 [OPTIONS...] <filename> | |
Convert a video to GIF. | |
Example: $0 -r24 -w320 -f3 video.mp4 | |
GIF format: | |
-r <fps>, set framerate | |
-w <width>, set width in pixel | |
Color optimizations: | |
-d <size>, enable color dithering with <size> pattern | |
-f <percent> enable color fuzzing | |
Output selection: | |
-o <filename>, output to <filename> | |
Other options: | |
-i, open folder after image extraction and before conversion | |
EOF | |
exit 1 | |
} | |
function cleanup(){ | |
echo "Cleaning up, please wait." | |
rm -rf $TMPDIR | |
} | |
while getopts "h?w:r:f:d:o:i" opt; do | |
case "$opt" in | |
h|\?) | |
usage | |
;; | |
f) | |
CONVERT_OPT="${CONVERT_OPT} -fuzz ${OPTARG}%" | |
;; | |
w) | |
FFMPEG_OPT="${FFMPEG_OPT} -vf scale=${OPTARG}:-1" | |
;; | |
r) | |
FFMPEG_OPT="${FFMPEG_OPT} -r ${OPTARG}" | |
CONVERT_OPT="${CONVERT_OPT} -delay 1/${OPTARG}" | |
;; | |
o) | |
OUTPUT=$OPTARG | |
;; | |
d) | |
CONVERT_OPT="${CONVERT_OPT} -ordered-dither o${OPTARG}x${OPTARG},8,8,4" | |
;; | |
i) | |
INSPECT=1 | |
;; | |
*) | |
usage "unknow argument -$opt" | |
;; | |
esac | |
done | |
if command -v avconv >/dev/null 2>&1; then | |
FFMPEG=avconv | |
elif command -v ffmpeg >/dev/null 2>&1; then | |
FFMPEG=ffmpeg | |
else | |
echo -e >&2 "error: avconv or ffmpeg is required but is not installed. Aborting." | |
exit 2; | |
fi | |
ensure_installed convert | |
shift $((OPTIND-1)) | |
FILENAME=$1 | |
if [[ -z "$FILENAME" ]]; then | |
usage "error: missing input argument" | |
fi | |
if [[ -z "$OUTPUT" ]]; then | |
OUTPUT=${FILENAME%.*}.gif | |
fi | |
trap cleanup 0 | |
TMPDIR=`mktemp -d` | |
$FFMPEG -i $FILENAME $FFMPEG_OPT -f image2 $TMPDIR/%04d.png | |
test -n "$INSPECT" && echo -n "Opening $TMPDIR : " && xdg-open $TMPDIR && read -p "press any key to continue..." | |
convert $CONVERT_OPT `ls $TMPDIR/*.png` -coalesce -layers RemoveDups -layers Optimize +map $OUTPUT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment