Converting my website images to webP

🌻 Plant |

I wanted to reduce the file size of my image assets. At this point in time I'm not serving many images, but I wanted to ensure the web performance is as best it can be. I decided to go down the route of storing the webP image format assets in an AWS S3 Bucket1 and deliver those with AWS Cloudfront2.

With a little help from Claude, I created a Python script that converts SUPPORTED_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff'} into webP format3.

Firstly, I setup a folder webp-converter this housed the Python script. I then created the following folder images-to-convert, this contains all my original image assets ready to be converted.

Inside the directory webp-converter using the folllowing command python3 webp-converter.py runs the script to convert images into the webP image format. The images are then stored in the webp_converted folder ready for S3.

Once I was happy the script worked, I then asked Claude to add detailed comments:

from PIL import Image # Pillow library for image processing
import os
from pathlib import Path # Path for more reliable file path handling across OS
def convert_to_webp(source_dir, quality=80):
"""
Convert all images in the source directory to WebP format.
Args:
source_dir (str): Directory containing the images to convert
quality (int): WebP quality setting (0-100). Higher values = better quality but larger files
80 is a good balance between quality and file size
"""
# Define which file extensions we'll process
# Only files with these extensions will be converted to WebP
SUPPORTED_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff'}
# Create an output directory for the WebP files
# Using Path ensures this works on both Windows and Mac/Linux
output_dir = Path(source_dir) / 'webp_converted'
# exist_ok=True means it won't raise an error if the directory already exists
output_dir.mkdir(exist_ok=True)
# Get all image files from the source directory
# This list comprehension does several things:
# 1. iterdir() lists all files in the directory
# 2. Checks if each file's extension is in our SUPPORTED_FORMATS
# 3. Verifies it's a file (not a directory)
image_files = [
f for f in Path(source_dir).iterdir()
if f.suffix.lower() in SUPPORTED_FORMATS and f.is_file()
]
print(f"Found {len(image_files)} images to convert")
# Process each image one at a time
for img_path in image_files:
try:
# Open the image file
with Image.open(img_path) as img:
# Handle different image modes
# Some images (like PNGs) might have transparency (RGBA mode)
# or be in a different color mode that WebP doesn't support
if img.mode in ('RGBA', 'LA'):
# If image has transparency, create a white background
background = Image.new('RGB', img.size, (255, 255, 255))
# Paste the image onto the white background using the alpha channel as mask
background.paste(img, mask=img.split()[-1])
img = background
elif img.mode != 'RGB':
# Convert any other mode to RGB
img = img.convert('RGB')
# Create the output filename
# We keep the original filename but change the extension to .webp
output_path = output_dir / f"{img_path.stem}.webp"
# Save the image in WebP format
# quality parameter controls the compression level
img.save(output_path, 'WEBP', quality=quality)
print(f"Converted: {img_path.name} -> {output_path.name}")
except Exception as e:
# If anything goes wrong with this particular image,
# print an error but continue processing other images
print(f"Error converting {img_path.name}: {e}")
print("\nConversion complete!")
print(f"Converted images can be found in: {output_dir}")
# This is the entry point of the script
if __name__ == "__main__":
# MODIFY THIS PATH to point to your images directory
# Example paths:
# Windows: "C:\\Users\\YourName\\Pictures\\images-to-convert"
# Mac/Linux: "/Users/YourName/Pictures/images-to-convert"
IMAGE_DIRECTORY = "{PATH=}/webp-converter/images-to-convert"
print("Starting image conversion...")
# Call the conversion function with our specified directory
convert_to_webp(IMAGE_DIRECTORY)
view raw webp-converter.py hosted with ❀ by GitHub
3

WebP is a modern image format that provides superior lossless and lossy compression for images on the web. Using WebP, webmasters and web developers can create smaller, richer images that make the web faster.