Converting an mp4 to an animated avif
Why?
avif files are the modern alternative to gifs. Better quality at much smaller file sizes. This means your site page loads faster with an avif than with a gif.
How
This tutorial is for mac. The steps should be similar on windows.
Ensure you have ffmpef
and libavif
installed. You can do so with brew using the following command:
brew install ffmpeg libavif
Then, open up a terminal and navigate to the directory where your .mp4 file is saved, and run the following command:
ffmpeg -i input.mp4 -pix_fmt yuv420p -f yuv4mpegpipe output.y4m
Make sure you replace input.mp4
with your actual filename.
After the above command is completed, run the following command:
avifenc output.y4m animated.avif
And there you have it! You can open up the animated.avif and see your animation. Please note that as of writing this, MacOS doesn't natively support viewing animated avif files. Insead, if you try opening the file using MacOS' native Preview app, you will see a static frame. To properly view the animated avif file, you can use a third-party solution like IINA media player.
To speed up this process, I've created a bash script you can use so you don't have to run these commands separately each time. Here are the steps:
Create a new file named
mp4_to_avif.sh
.Copy and paste the following code into the file:
#!/bin/bash
if [ -z "$1" ]; then
echo "Please provide the input mp4 file name."
exit 1
fi
if [ ! -f "$1" ]; then
echo "File $1 does not exist."
exit 1
fi
ffmpeg -i "$1" -pix_fmt yuv420p -f yuv4mpegpipe output.y4m
if [ $? -ne 0 ]; then
echo "Error converting mp4 to y4m."
exit 1
fi
avifenc output.y4m animated.avif
if [ $? -ne 0 ]; then
echo "Error converting y4m to avif."
exit 1
fi
echo "Conversion successful. Result saved as animated.avif."
Make the script executable by running:
chmod +x mp4_to_avif.sh
. Ensure you are in the same directory as the file.Then, while still remaining in the same directory as the script, you can run the script with your mp4 file as an argument:
./mp4_to_avif.sh input.mp4
.Note: This command assumes that your
mp4_to_avif.sh
andinput.mp4
are in the same directory. If they're not, simply replaceinput.mp4
with the path to the file. Here's an example:./mp4_to_avif.sh /Users/videos/input.mp4
. Once again, for this command to work, you have to be in the same directory as themp4_to_avif.sh
file.
The script checks if the input file exists, then runs the commands one after the other, checking for errors after each step. If any step fails, the script prints an error message and exits.
Make sure that both ffmpeg
and libavif
are installed and available in your PATH for the script to work properly.
Check out the source code on GitHub. I hope you've found this guide useful - feel free to follow me on Twitter!
References:
Subscribe to my newsletter
Read articles from Dan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by