BOBOBK

Python Converts All Site Images to WebP Format

TECHNOLOGY

You might have noticed that almost all images on this site use the WebP format. So, what is WebP? WebP is an image file format developed by Google that provides both lossy and lossless compression. The WebP image format can significantly reduce file size while achieving the same image quality as the JPEG format, thereby significantly reducing the time it takes for image files to be sent over the network and saving network traffic. According to earlier tests by Google, WebP’s lossless compression results in 45% smaller file sizes compared to PNG files found online. Furthermore, most browsers already support this excellent technology. Therefore, for saving network resources, adopting the WebP format for the entire site is ideal, and using Python to handle this is very convenient. Here, I will introduce how to use Python to convert various image formats like JPG, JPEG, and PNG to WebP.


First Step: Install the Pillow Package

pip install Pillow

Second Step: Start Converting to WebP

from PIL import Image

imagePath = "bingchuan.jpg" # Input file name

outputPath = "bingchuan.webp" # Output file name
im = Image.open(imagePath) # Read the file
im.size # Can view image size
im.thumbnail((1200,900), Image.ANTIALIAS) # Reset image size
im.save(outputPath) # Save

Third Step: Batch Convert Images to WebP

from PIL import Image
from os import walk
import os # Import the os module

def pic_webp(picpath):
    imagePath = picpath.split(".")[0]
    # File name
    outputPath = imagePath + ".webp"
    # Output file name
    im = Image.open(picpath) # Read the file (changed from imagePath to picpath)
    im.save(outputPath) # Save

for (dirpath, dirname, dirfile_list) in os.walk("./"): # Changed dirfile to dirfile_list
    for dirfile in dirfile_list: # Iterate through the list of files
        if dirfile.split(".")[-1].lower() in ["png","jpeg","jpg"]: # Improved file extension check and made it case-insensitive
            pic_webp(os.path.join(dirpath, dirfile)) # Use os.path.join for correct path construction

With just a few lines of code, you can convert all PNG, JPEG, and JPG images in the current directory to WebP format. Of course, to replace all images on a website, you also need to modify the image paths in the database. You will need to operate on different data tables depending on your CMS. Go ahead and give it a try!

Related