当前位置: 移动技术网 > IT编程>脚本编程>Python > Python将图片批量从png格式转换至WebP格式

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

因为是女子音译歌词,儿女传奇之咒怨新娘,擦边网

实现效果

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


源图片目录


目标图片目录

关于批量生成1000张图片,可以参考这篇文章:

实现示例

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参数为目标格式。

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网