Created
December 30, 2023 23:36
-
-
Save tjb0607/85594082ff54ce51669a5f9487aa3e4b to your computer and use it in GitHub Desktop.
vid2gif.sh - uses ffmpeg and gifsicle to convert a video to a gif within a filesize constraint
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 | |
echo "Usage: vid2gif.sh <input> <output>" | |
echo -n "Enter desired delay (1/100 of seconds): " | |
read delay | |
fps=$(expr 100 / $delay) | |
read -p "Enter width [default: -1]: " width | |
width=${width:--1} | |
read -p "Enter height [default: -1]: " height | |
height=${height:--1} | |
read -p "Enter start timestamp [default: 0]: " tstart | |
tstart=${tstart:-0} | |
read -p "Enter duration [default: 9999999]: " dur | |
dur=${dur:-9999999} | |
read -p "Enter extra ffmpeg filters (put a comma first): " ffextra | |
read -p "Enter maximum filesize (bytes) [default: 3145728]: " maxbytes | |
maxbytes=${maxbytes:-3145728} | |
tempdir=$(mktemp -d) | |
filters="fps=$fps,scale=$width:$height:flags=lanczos$ffextra" | |
ffmpeg -v warning -ss $tstart -t $dur -i "$1" -vf "$filters,palettegen" -y $tempdir/palette.png | |
ffmpeg -v warning -ss $tstart -t $dur -i "$1" -i $tempdir/palette.png -lavfi "$filters [x]; [x][1:v] paletteuse=dither=floyd_steinberg" -y $tempdir/gif.gif | |
rm "$2" | |
gifsicle -O3 -j7 -d $delay -o "$2" $tempdir/gif.gif | |
lossy=0 | |
#increment loss until filesize target is reached. | |
while [ $(stat -c%s "$2") -gt $maxbytes ] && [ $lossy -lt 200 ]; do | |
echo "Lossy setting $lossy didn't work (filesize = $(bc <<< 'scale=6; '$(stat -c%s "$2")'/1048576') MiB), tring $(($lossy + 5))" | |
lossy=$(($lossy + 5)) | |
rm "$2" | |
gifsicle -O3 -j7 --lossy=$lossy -d $delay -o "$2" $tempdir/gif.gif | |
done | |
rm -r $tempdir | |
echo ----------- | |
if [ $lossy -gt 0 ]; then | |
echo "Done! Used lossy setting $lossy, filesize = $(bc <<< 'scale=6; '$(stat -c%s "$2")'/1048576') MiB" | |
else | |
echo "Done! Didn't need lossy compression, filesize = $(bc <<< 'scale=6; '$(stat -c%s "$2")'/1048576') MiB" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment