Python Script for Converting PNG/JPG files to WebP
During the creation of this script, I have tested multiple images with decent reductions in size and minimal quality loss. I have provided examples of quality and size at the end of this post.
Environment setup
Create a folder on your computer and name it WebPConverter or anything you desire. Within this folder we will want to create the convert.py file and a folder named bulk_images. You will want to place your PNG/JPG images within this folder.
The folder structure should look like the bellow:
WebP Conversion Script
Step 1
We will be using 2 libraries for this, Path and PIL. Path comes as standard with python but PIL will need to be installed with the below command: pip install Pillow We will then want to import both libraries:
from pathlib import Path
from PIL import Image
Step 2
Now you will need to create a convert_files function that will process the actual image conversion.
def convert_files(input):
file_name = input.with_suffix(".webp")
image = Image.open(input)
image.save(file_name, format="webp")
return file_name
This will be taking an input of the file name/location and outputting the file with the same name but in a WebP format.
Step 3
We will now make a gather_input function that will find the files in either a JPG or PNG format and push those to the convert_files function.
def gather_input():
pngs = Path("bulk_images").glob("*.png")
jpgs = Path("bulk_images").glob("*.jpg")
for png in pngs:
png_to_webp_path = convert_files(png)
print(png_to_webp_path)
for jpg in jpgs:
jpg_to_webp_path = convert_files(jpg)
print(jpg_to_webp_path)
Step 4
Now you will just want to call the latter function and the script will convert all files within the bulk_images folder.
gather_input()
After some testing, it takes roughly around 1 minute to convert 200 images, so in many cases, this can be a huge time saver.
Examples I have tested two images one PNG and one JPG and hosted them on this page to showcase the difference in size and why WebP is a much more efficient image format overall.
Image1 (JPG) = 224 kb Image1 (WebP) = 80 kb Image2 (JPG) = 64 kb Image2 (WebP) = 44 kb
Final Code
from pathlib import Path
from PIL import Image
def convert_files(input):
file_name = input.with_suffix(".webp")
image = Image.open(input)
image.save(file_name, format="webp")
return file_name
def gather_input():
pngs = Path("bulk_images").glob("*.png")
jpgs = Path("bulk_images").glob("*.jpg")
for png in pngs:
png_to_webp_path = convert_files(png)
print(png_to_webp_path)
for jpg in jpgs:
jpg_to_webp_path = convert_files(jpg)
print(jpg_to_webp_path)
gather_input()
If there are any questions regarding this script or any improvements that could be made, please don't hesitate to contact me.