将位于 /img 目录下的1000张 .png 图片,转换成 .webp 格式,并存放于 img_webp 文件夹内。
源图片目录
目标图片目录
关于批量生成1000张图片,可以参考这篇文章:利用Python批量生成任意尺寸的图片
实现示例
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 参数为目标格式。
好了,这篇文章的内容到这就基本结束了,大家都学会了吗?希望对大家的学习和工作能有一定的帮助。
更多Python将图片批量从png格式转换至WebP格式相关文章请关注PHP中文网!
查看更多关于Python将图片批量从png格式转换至WebP格式的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did82713