使用python脚本将文件夹中的所有图像转换为.webp

问题描述 投票:2回答:1

我一直在研究网站的图像,并发现.webp格式比.jpeg.png更加紧凑,在Docs上找到更多。

现在我有一个包含近25张图像的文件夹,我想将所有图像转换为.webp格式。任何人都可以建议我如何使用python脚本转换所有,而不使用在线工具。

python html python-3.x webp
1个回答
2
投票

首先,你必须根据你的机器(Windows | Linux)从here下载cwebp压缩器工具。

现在在C:\Program Files\中提取文件夹后你必须set pathcwebp.exe,下面是我的路径Path:: C:\Program Files\libwebp\bin

打开cmd以检查您是否已完成此操作。

  • cmd> cwebp -version

cwebp- version

  • cmd> python --version

python --version

现在,只需运行以下脚本就可以轻松获得所需的输出,也可以从here下载github上的repo

# --cwebp_compressor.py--

# cmd> python cwebp_compressor.py folder-name 80

import sys
from subprocess import call
from glob import glob

#folder-name
path = sys.argv[1]
#quality of produced .webp images [0-100]
quality = sys.argv[2]

if int(quality) < 0 or int(quality) > 100:
    print("image quality out of range[0-100] ;/:/")
    sys.exit(0)

img_list = []
for img_name in glob(path+'/*'):
    # one can use more image types(bmp,tiff,gif)
    if img_name.endswith(".jpg") or img_name.endswith(".png") or img_name.endswith(".jpeg"):
        # extract images name(image_name.[jpg|png]) from the full path
        img_list.append(img_name.split('\\')[-1])


# print(img_list)   # for debug
for img_name in img_list:
    # though the chances are very less but be very careful when modifying the below code
    cmd='cwebp \"'+path+'/'+img_name+'\" -q '+quality+' -o \"'+path+'/'+(img_name.split('.')[0])+'.webp\"'
    # running the above command
    call(cmd, shell=False)  
    # print(cmd)    # for debug
© www.soinside.com 2019 - 2024. All rights reserved.