网络编程
位置:首页>> 网络编程>> Python编程>> Python将图片批量从png格式转换至WebP格式

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

作者:daisy  发布时间:2023-01-11 00:27:49 

标签:python,png,webp

实现效果

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

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

Python将图片批量从png格式转换至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参数为目标格式。

下面是其他网友的补充

WebP与PNG, JPEG的转换

webp文件是的谷歌制定的文件,编码和解码当然要用谷歌自己提供的工具libwebp,别整那些有的没的的方法。
如果再pc上的浏览器(如Chrome,Edge等)打开微信的推送,爬虫爬取到图片可能就是webp格式的

1、下载对应平台的libwebp

2、解压得到二进制文件,在bin目录下(编程的使用include和lib目录下的文件),以下是以windows 64bit为例,摘自readme.txt。详细的可以使用-h选项查看具体的用法。

path/to/filedescription
bin/cwebp.exeencoding tool
bin/dwebp.exedecoding tool
bin/gif2webp.exegif conversion tool
bin/vwebp.exewebp visualization tool
bin/webpinfo.exewebp analysis tool
lib/static libraries
include/webpheaders
test.webpa sample WebP file
test_ref.ppmthe test.webp file decoded into the PPM format

3、其他 --> webp: cwebp [-preset <...>] [options] in_file [-o out_file]
4、webp --> 其他: dwebp in_file [options] [-o out_file]

  • 不指明格式默认转成PNG格式

  • webp文件名不能有空格

5、批量转的话那就是脚本的事了,例如Python3脚本批量将webp转png(转换成png后再转成其他格式就很简单了):


import os
import sys

decoder_path = r"path/to/dwebp.exe" # Windows10下其实也支持斜杠/路径
webp_path = r"path/to/webp" # webp文件所在目录,webp文件名不能有空格!
res_path = r"path/to/png_res" # 存储转换后图片的目录,假设是png

if not os.path.exists(res_path) :
 os.mkdir("result")

for f in os.listdir(webp_path):
 res_f = str(f).replace(".webp", ".png") # 若webp文件命名有特殊,这里需要改改映射规则
 cmd = "{0} {1} -o {2}".format(
   decoder_path, os.path.join(webp_path, f), os.path.join(res_path, res_f))
 os.system(cmd)

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

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com