春江暮客

春江暮客的个人学习分享网站

Python Converts All Site Images to WebP Format

2018-12-04 Technology
Python Converts All Site Images to WebP Format

If you care about page speed, image format is usually one of the easiest optimization targets. WebP, developed by Google, supports both lossy and lossless compression and can often reduce image size significantly for web delivery.

When a site has many images, using Python to convert them in batches is much more practical than editing them one by one. This article shows how to convert JPG, JPEG, and PNG images to WebP with Pillow.


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

If you are using a newer Pillow release, Image.ANTIALIAS may be deprecated. In that case, replace it with Image.Resampling.LANCZOS.

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. On a real website, though, file conversion is only part of the job. You also need to update image references in the database or article content, depending on how your CMS stores media paths.

In practice, back up the original images before running a full-site batch conversion. That makes rollbacks much easier if a theme, plugin, or compatibility rule still expects the old files.

友情链接

其它