当前位置:Gxlcms > Python > Python将图片批量从png格式转换至WebP格式

Python将图片批量从png格式转换至WebP格式

时间:2021-07-01 10:21:17 帮助过:9人阅读

实现效果

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

Python将图片批量从png格式转换至WebP格式
源图片目录

Python将图片批量从png格式转换至WebP格式
目标图片目录

关于批量生成1000张图片,可以参考这篇文章:利用Python批量生成任意尺寸的图片

实现示例

  1. import glob
  2. import os
  3. import threading
  4. from PIL import Image
  5. def create_image(infile, index):
  6. os.path.splitext(infile)
  7. im = Image.open(infile)
  8. im.save("img_webp/webp_" + str(index) + ".webp", "WEBP")
  9. def start():
  10. index = 0
  11. for infile in glob.glob("img/*.png"):
  12. t = threading.Thread(target=create_image, args=(infile, index,))
  13. t.start()
  14. t.join()
  15. index += 1
  16. if __name__ == "__main__":
  17. start()

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

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

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

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

好了,这篇文章的内容到这就基本结束了,大家都学会了吗?希望对大家的学习和工作能有一定的帮助。

更多Python将图片批量从png格式转换至WebP格式相关文章请关注PHP中文网!

人气教程排行