使用Python批量将图片转换至WebP格式

1507 查看

0x00 背景

因检验需要,现需要将1000张图片(如何批量生成图片?Abel Joo的简书),从.png格式转换至.webp格式。

0x01 效果

实现目标:将位于/img目录下的1000.png图片,转换成.webp格式,并存放于img_webp文件夹内。


源图片目录

目标图片目录

0x02 实现

Read the fucking code:

import glob
import os
import threading

from PIL import Image


def create_image(infile, index):
    os.path.splitext(infile)
    im = Image.open(infile)
    im.save("img_webp/webp_" + str(index) + ".webp", "WEBP")


def start():
    index = 0
    for infile in glob.glob("img/*.png"):
        t = threading.Thread(target=create_image, args=(infile, index,))
        t.start()
        t.join()
        index += 1


if __name__ == "__main__":
    start()

注意,该项目需要引用PIL库。

考虑到是大量的线性密集型运算,因此使用了多线程并发。通过threading.Thread()创建线程对象时注意,args参数仅接受元祖。

在这里,我们使用Image.open()函数打开图像。

最终调用save("img_webp/webp_" + str(index) + ".webp", "WEBP")方法,以指定格式写入指定位置。其中format参数为目标格式。