Convert All Your Images to WebP (Python Script)
- → WebP gives up to 80% smaller file sizes than JPEG/PNG
- → All modern browsers support it since 2020
- → Use the Python script to batch convert entire directories
- → Faster pages = better Core Web Vitals = better rankings
In This Guide
Why WebP?
Google released WebP over a decade ago, and in that time it's proven itself capable of delivering up to 80% reduction in image file size with minimal perceptible impact on quality, which means you can serve images that look essentially the same to human eyes but weigh a fraction of what JPEGs and PNGs weigh, and since 2020 when Safari finally got on board, WebP has been supported by all modern browsers, so if you're still serving those bloated legacy formats you're leaving page speed on the table for no good reason.
The Problem
The problem is that converting images to WebP has historically been a pain, because the solutions available are either slow resource-heavy plugins that murder your server's CPU while your actual visitors wait, or online tools that charge outrageous fees for something that should be trivially simple, or the medieval approach of doing it manually one by one in Photoshop or some other image editor, which is exactly the kind of tedious busywork that computers were supposed to save us from.
The Script
This Python script scans your images directory and all subdirectories, recursively converting everything it finds to WebP, which means you can point it at your entire images folder and walk away while it does the work, and when you come back you'll have WebP versions of everything, fast and free.
import os
import PIL
from PIL import Image
MY_DIR = "." # Your images directory
for root, dirs, files in os.walk(MY_DIR):
for _this_file in files:
if _this_file.endswith('.webp'):
continue
_source = root + os.sep + _this_file
try:
im = Image.open(_source).convert("RGB")
im.save(_source.rsplit('.', 1)[0] + ".webp", "webp")
except PIL.UnidentifiedImageError:
pass
How to Use It
Step 1: Install Pillow
First you need the Pillow library, which is Python's go-to image processing toolkit, so open your terminal and run the pip install command:
pip install pillow
Step 2: Run the Script
Save the script above as convert_webp.py, then update the MY_DIR variable to point to whatever folder contains your images, and execute it:
python convert_webp.py
Step 3: Done
That's genuinely it, and now all your images exist as WebP files alongside their original versions, which means the only remaining task is to update your HTML and CSS to reference the new .webp files instead of the old formats.