This post introduces a Python script that automates the conversion of images into the AVIF format.
What is the AVIF Format?
AVIF is a modern image format based on the AV1 video codec.
It offers:
- very high compression rates
- excellent image quality even at low bitrates
- smaller file sizes compared to JPEG or PNG
Particularly for websites, AVIF is interesting because it reduces loading times and bandwidth usage without visible quality loss.
Overview of the Script
The following Python script uses the standard libraries os and subprocess to:
- Find images in a source folder
- Convert them to the AVIF format using FFmpeg
- Output the file size savings per file
It supports PNG, JPG, and JPEG files by default.
Python Script for AVIF Conversion
import os
import subprocess
def convert_to_avif(source_folder, output_folder):
# Ensure the output folder exists
if not os.path.exists(output_folder):
os.makedirs(output_folder)
total_files = 0
converted_files = 0
# Iterate through all files in the source directory
for filename in os.listdir(source_folder):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
total_files += 1
source_file = os.path.join(source_folder, filename)
output_file = os.path.join(
output_folder,
os.path.splitext(filename)[0] + '.avif'
)
original_size = os.path.getsize(source_file)
command = [
'ffmpeg',
'-i', source_file,
'-c:v', 'libaom-av1',
'-crf', '30',
'-preset', 'slow',
output_file
]
try:
subprocess.run(
command,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
converted_files += 1
new_size = os.path.getsize(output_file)
reduction_percent = 100 * (1 - (new_size / original_size))
print(f"{filename}: reduced by {reduction_percent:.2f}%.")
except subprocess.CalledProcessError as e:
print(f"Error converting: {source_file} – {e}")
print(
f"Conversion completed. "
f"{converted_files} of {total_files} files were converted."
)
# Adjust paths
source_folder = ""
output_folder = ""
convert_to_avif(source_folder, output_folder)
Notes Before Running
- Adjust the source and target folders in the script
- Make sure FFmpeg is installed
- FFmpeg can be downloaded from the official website if needed
After running, all supported images will be converted automatically and the respective size reduction will be printed.