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.
- 原文作者:春江暮客
- 原文链接:https://www.bobobk.com/en/78.html
- 版权声明:本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。