我们可以使用python转换图片文件到webp格式以提升网站访问速度
#
Python把图片批量转换为webp
需要Python 3.8.10,我不想使用在线转换awa
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 | import os
import sys
from PIL import Image
def convert_to_webp(input_file, output_file, quality=80):
    try:
        with Image.open(input_file) as im:
            im.save(output_file, "webp", quality=quality)
        print(f"Converted: {input_file} => {output_file}")
    except Exception as e:
        print(f"Error converting file: {input_file}")
        print(str(e))
def process_folder(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for filename in files:
            if any(filename.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.png']):
                input_file = os.path.join(root, filename)
                output_file = os.path.splitext(input_file)[0] + ".webp"
                convert_to_webp(input_file, output_file)
if __name__ == "__main__":
    folder_path = os.path.dirname(sys.argv[0])
    process_folder(folder_path)
 | 
#
注释版本
这段代码的功能是批量将文件夹内的JPG、JPEG和PNG图片转换为WEBP格式。
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 | import os     # 处理文件和目录
import sys # 获取命令行参数
from PIL import Image # 处理图片
def convert_to_webp(input_file, output_file, quality=80):
 # 函数用于转换一个图片文件
 # input_file: 输入的图片文件路径  
 # output_file: 输出的webp文件路径
 # quality: webp文件质量,取值范围1-100,默认值80
 try:
 # 打开输入图片文件
 with Image.open(input_file) as im:
 # 保存为webp格式
 im.save(output_file, "webp", quality=quality) 
print(f"Converted: {input_file} => {output_file}")
 except Exception as e:
 # 捕获异常
 print(f"Error converting file: {input_file}")
 print(str(e))
def process_folder(folder_path):
 # 函数用于处理整个文件夹
 # folder_path: 文件夹路径
 for root, dirs, files in os.walk(folder_path):
 for filename in files:
 # 检查文件后缀是否为jpg/jpeg/png
 if any(filename.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.png']):
 input_file = os.path.join(root, filename)
 output_file = os.path.splitext(input_file)[0] + ".webp"
 # 调用转换函数
 convert_to_webp(input_file, output_file)
if __name__ == "__main__":
 # 获取当前脚本路径
 folder_path = os.path.dirname(sys.argv[0]) 
process_folder(folder_path)
 | 
#
需要安装的库
以下是安装Pillow库的步骤:
- 确保已经安装Python环境。 
- 打开命令提示符(Windows)或终端(Mac/Linux)。 
- 输入以下命令安装Pillow: 
- 安装成功后,可以导入Pillow库进行图像处理: 
- 如果遇到权限问题,可以使用sudo或加入管理员权限安装: | 1
 | sudo pip install Pillow
 |  
 
| 1
 | pip install Pillow --user
 |  
 
- 在Windows中,您有时需要使用pip install -U Pillow命令升级pip以安装Pillow。 
- Pillow还有一些依赖,所以在安装期间可能也需要安装这些依赖。 
示例安装命令:
- linux系统/Mac: pip install Pillow
- Windows: pip install Pillow或pip install Pillow --user
主要步骤就是使用pip安装Pillow库,然后就可以在Python代码中导入 PIL包并使用Pillow了。
#
后记
完美实现了转换webp的要求