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

5
我一直在处理网站上的图片,并发现 .webp 格式比 .jpeg.png 更紧凑,更多信息请参见文档

现在我有一个包含近25张图片的文件夹,我想将所有图片转换为 .webp 格式。有没有人能建议我如何使用Python脚本批量转换而不使用在线工具?

3个回答

4

首先,您需要根据您的操作系统(Windows|Linux)从此处下载cwebp压缩工具。

现在,在C:\Program Files\文件夹中解压缩后,您需要设置路径cwebp.exe文件。以下是我的路径:Path:: C:\Program Files\libwebp\bin

打开cmd命令行,检查您到目前为止是否做得正确。

  • cmd> cwebp -version

cwebp- version

  • cmd> python --version

python --version

现在非常容易,只需运行下面的脚本即可获得所需的输出,或者您可以从此处下载我的github库。

# --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

为什么不同时使用-near_lossless 80和有损压缩,然后选择较小的呢? - Jyrki Alakuijala
@JyrkiAlakuijala,当我开始进行WebP转换时,我发现逐个转换所有25张图片很繁琐......上面的代码更多地是批量图像转换......好吧,你可以在你的代码中实现这个......好主意。 - Pankaj Kumar Gautam
我不得不将 call(cmd, shell=False) 更改为 call(cmd, shell=True),因为我们正在传递一个 shell 命令。参考 - eMad
谢谢!我根据自己的需求进行了修改(与shell一起使用,将文件保存在单独的文件夹中)。效果很好!我的版本:https://gist.github.com/apiwonska/d2a0938fc68909e14f83876e72a55325 - ann.piv

0

虽然这是一篇旧帖,但我想分享我的更新版本。它会要求您选择一个文件夹,在该文件夹及其子文件夹中递归地工作,并询问您所需的质量,告诉您已转换了多少图像。

首先,您需要安装cwebp和Python。

# --cwebp_compressor.py--

import sys
from subprocess import call
from glob import glob
import tkinter as tk
from tkinter import filedialog
import os
from tqdm import tqdm

# open a prompt to select the folder
root = tk.Tk()
root.withdraw()
path = filedialog.askdirectory()

# open a prompt to enter the desired quality
quality = input("Enter the desired quality (0-100): ")

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

img_list = []
jpg_count = 0
png_count = 0
jpeg_count = 0
bmp_count = 0
tiff_count = 0
for dirpath, _, filenames in os.walk(path):
    for img_name in filenames:
        # one can use more image types(bmp,tiff,gif)
        if img_name.endswith(".jpg"):
            jpg_count += 1
        elif img_name.endswith(".png"):
            png_count += 1
        elif img_name.endswith(".jpeg"):
            jpeg_count += 1
        elif img_name.endswith(".bmp"):
            bmp_count += 1
        elif img_name.endswith(".tiff") or img_name.endswith(".tif"):
            tiff_count += 1
        else:
            continue
        # extract images name(image_name.[jpg|png]) from the full path
        img_list.append(os.path.join(dirpath, img_name))

with tqdm(total=len(img_list), desc="Compressing Images") as pbar:
    for img_name in img_list:
        # though the chances are very less but be very careful when modifying the below code
        cmd='cwebp \"'+img_name+'\" -q '+quality+' -o \"'+os.path.splitext(img_name)[0]+'.webp\"'
        # running the above command
        call(cmd, shell=False)
        pbar.update(1)

print("Compression completed!\n")
print(f"The compressor converted and compressed {jpg_count} .jpg, {png_count} .png, {jpeg_count} .jpeg, {bmp_count} .bmp, and {tiff_count} .tiff files.")

input("Press Enter to exit...")


-1
又是一个死帖,但我想分享一下对我有效的更新。
首先,第一步与DevSolal的帖子相同,你需要安装cwebppython
其次,参考eMadann.piv评论,将call(cmd, shell=False)改为call(cmd, shell=True)
所以:
# --cwebp_compressor.py--

import sys
from subprocess import call
from glob import glob
import tkinter as tk
from tkinter import filedialog
import os
from tqdm import tqdm

# open a prompt to select the folder
root = tk.Tk()
root.withdraw()
path = filedialog.askdirectory()

# open a prompt to enter the desired quality
quality = input("Enter the desired quality (0-100): ")

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

img_list = []
jpg_count = 0
png_count = 0
jpeg_count = 0
bmp_count = 0
tiff_count = 0
for dirpath, _, filenames in os.walk(path):
    for img_name in filenames:
        # one can use more image types(bmp,tiff,gif)
        if img_name.endswith(".jpg"):
            jpg_count += 1
        elif img_name.endswith(".png"):
            png_count += 1
        elif img_name.endswith(".jpeg"):
            jpeg_count += 1
        elif img_name.endswith(".bmp"):
            bmp_count += 1
        elif img_name.endswith(".tiff") or img_name.endswith(".tif"):
            tiff_count += 1
        else:
            continue
        # extract images name(image_name.[jpg|png]) from the full path
        img_list.append(os.path.join(dirpath, img_name))

with tqdm(total=len(img_list), desc="Compressing Images") as pbar:
    for img_name in img_list:
        # though the chances are very less but be very careful when modifying the below code
        cmd='cwebp \"'+img_name+'\" -q '+quality+' -o \"'+os.path.splitext(img_name)[0]+'.webp\"'
        # running the above command
        call(cmd, shell=True)
        pbar.update(1)

print("Compression completed!\n")
print(f"The compressor converted and compressed {jpg_count} .jpg, {png_count} .png, {jpeg_count} .jpeg, {bmp_count} .bmp, and {tiff_count} .tiff files.")

input("Press Enter to exit...")

然后我运行了find . -name "*.tif" -type f -delete,以保持相同的目录结构,但使用WebP文件替代了TIFF文件。
(我本来想评论DevSolal的帖子,但是我没有权限...)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接