源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-09-06 02:42 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python将图片批量从png格式转换至WebP格式
[b]实现效果[/b] 将位于[code]/img[/code]目录下的1000张[code].png[/code]图片,转换成[code].webp[/code]格式,并存放于[code]img_webp[/code]文件夹内。 [img]http://img.1sucai.cn/uploads/article/2018010709/20180107090102_0_52498.jpg[/img] 源图片目录 [img]http://img.1sucai.cn/uploads/article/2018010709/20180107090103_1_48820.jpg[/img] 目标图片目录 关于批量生成1000张图片,可以参考这篇文章:[url=http://www.1sucai.cn/article/91492.htm]利用Python批量生成任意尺寸的图片[/url] [b]实现示例[/b]
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()
[b]注意:[/b]该项目需要引用[code]PIL[/code]库。 考虑到是大量的线性密集型运算,因此使用了多线程并发。通过[code]threading.Thread()[/code]创建线程对象时注意,[code]args[/code]参数仅接受元祖。 在这里,我们使用[code]Image.open()[/code]函数打开图像。 最终调用[code]save("img_webp/webp_" + str(index) + ".webp", "WEBP")[/code]方法,以指定格式写入指定位置。其中[code]format[/code]参数为目标格式。 好了,这篇文章的内容到这就基本结束了,大家都学会了吗?希望对大家的学习和工作能有一定的帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部