脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python将图片批量从png格式转换至WebP格式

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

2020-09-05 10:43Python教程网 Python

最近因为工作需要去研究了下png的压缩,发现转换成webp格式可以小很多,下面给大家分享利用Python将图片批量从png格式转换至WebP格式的方法,下面来一起看看。

实现效果

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

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

源图片目录

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

目标图片目录

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

实现示例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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/file description
bin/cwebp.exe encoding tool
bin/dwebp.exe decoding tool
bin/gif2webp.exe gif conversion tool
bin/vwebp.exe webp visualization tool
bin/webpinfo.exe webp analysis tool
lib/ static libraries
include/webp headers
test.webp a sample WebP file
test_ref.ppm the 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后再转成其他格式就很简单了):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)

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

延伸 · 阅读

精彩推荐