This note is written by Sheldon. You can find me with #iOSBySheldon in Github, Youtube, Facebook, etc.
Convert .mov/.MP4 to .gif
As a developer, I feel better to upload a short video when I create the pull request to show other viewers what I did in this PR. I tried .mov format directly got after finishing recording screen using Quicktime, however, gif offers preview in most web pages, and has smaller file size.
This is not limited to developer, anyone has this need can use this method to convert the files.
I tried to use some software to do the job, but my hands are tied since I don't have admin in my office comupter, but I do have brew installed. And I think using command line tool will be a good choice. So I will use HomeBrew, ffmpeg, gifsicle to do the job.
- download HomeBrew
$brew install ffmpeg
$brew install gifsicle
$ffmpeg -i in.mov -pix_fmt rgb8 -r 10 output.gif && gifsicle -O3 output.gif -o output.gif
- Convert the file to gif using
ffmpeg
- input path argument `-i`
- pixel format argument `-pix_fmt`
- removing some frames using framerate argument `-r`
- end `ffmpeg` with new path/to/filename
- Optimize the same output file with third option
-O3
and rewrite the generated gif file from last step - Notes: using
&&
to make sure the conversion sucess before optimizing
- https://brew.sh
- https://www.ffmpeg.org
- https://www.lcdf.org/gifsicle/
- full video tutorial with explanation https://www.youtube.com/watch?v=QKtRMFvvDL0
You can define the below function and add it to your .bashrc
or the like for use at anytime:
function v2g() {
src="" # required
target="" # optional (defaults to source file name)
resolution="" # optional (defaults to source video resolution)
fps=10 # optional (defaults to 10 fps -- helps drop frames)
while [ $# -gt 0 ]; do
if [[ $1 == *"--"* ]]; then
param="${1/--/}"
declare $param="$2"
fi
shift
done
if [[ -z $src ]]; then
echo -e "\nPlease call 'v2g --src <source video file>' to run this command\n"
return 1
fi
if [[ -z $target ]]; then
target=$src
fi
basename=${target%.*}
[[ ${#basename} = 0 ]] && basename=$target
target="$basename.gif"
if [[ -n $fps ]]; then
# fps="-r $fps"
fps=""
echo "FPS is IGNORED for now"
fi
if [[ -n $resolution ]]; then
resolution="-s $resolution"
fi
echo "ffmpeg -i "$src" -pix_fmt rgb8 $fps $resolution "$target" && gifsicle -O3 "$target" -o "$target""
ffmpeg -i "$src" -pix_fmt rgb8 $fps $resolution "$target" && gifsicle -O3 "$target" -o "$target"
osascript -e "display notification \"$target successfully converted and saved\" with title \"v2g complete\""
}
You can then call it as such
v2g --src orig.mp4 --target newname --resolution 800x400 --fps 30