欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python將圖片批量從png格式轉(zhuǎn)換至WebP格式

 更新時(shí)間:2020年08月22日 22:28:44   投稿:daisy  
最近因?yàn)楣ぷ餍枰パ芯苛讼聀ng的壓縮,發(fā)現(xiàn)轉(zhuǎn)換成webp格式可以小很多,下面給大家分享利用Python將圖片批量從png格式轉(zhuǎn)換至WebP格式的方法,下面來(lái)一起看看。

實(shí)現(xiàn)效果

將位于/img目錄下的1000張.png圖片,轉(zhuǎn)換成.webp格式,并存放于img_webp文件夾內(nèi)。


源圖片目錄


目標(biāo)圖片目錄

關(guān)于批量生成1000張圖片,可以參考這篇文章:利用Python批量生成任意尺寸的圖片

實(shí)現(xiàn)示例

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()

注意:該項(xiàng)目需要引用PIL庫(kù)。

考慮到是大量的線性密集型運(yùn)算,因此使用了多線程并發(fā)。通過(guò)threading.Thread()創(chuàng)建線程對(duì)象時(shí)注意,args參數(shù)僅接受元祖。

在這里,我們使用Image.open()函數(shù)打開(kāi)圖像。

最終調(diào)用save("img_webp/webp_" + str(index) + ".webp", "WEBP")方法,以指定格式寫(xiě)入指定位置。其中format參數(shù)為目標(biāo)格式。

下面是其他網(wǎng)友的補(bǔ)充

WebP與PNG, JPEG的轉(zhuǎn)換

webp文件是的谷歌制定的文件,編碼和解碼當(dāng)然要用谷歌自己提供的工具libwebp,別整那些有的沒(méi)的的方法。
如果再pc上的瀏覽器(如Chrome,Edge等)打開(kāi)微信的推送,爬蟲(chóng)爬取到圖片可能就是webp格式的

1、下載對(duì)應(yīng)平臺(tái)的libwebp

2、解壓得到二進(jìn)制文件,在bin目錄下(編程的使用include和lib目錄下的文件),以下是以windows 64bit為例,摘自readme.txt。詳細(xì)的可以使用-h選項(xiàng)查看具體的用法。

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]

  • 不指明格式默認(rèn)轉(zhuǎn)成PNG格式
  • webp文件名不能有空格

5、批量轉(zhuǎn)的話那就是腳本的事了,例如Python3腳本批量將webp轉(zhuǎn)png(轉(zhuǎn)換成png后再轉(zhuǎn)成其他格式就很簡(jiǎn)單了):

import os
import sys

decoder_path = r"path/to/dwebp.exe" # Windows10下其實(shí)也支持斜杠/路徑
webp_path = r"path/to/webp" # webp文件所在目錄,webp文件名不能有空格!
res_path = r"path/to/png_res" # 存儲(chǔ)轉(zhuǎn)換后圖片的目錄,假設(shè)是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文件命名有特殊,這里需要改改映射規(guī)則
  cmd = "{0} {1} -o {2}".format(
    decoder_path, os.path.join(webp_path, f), os.path.join(res_path, res_f))
  os.system(cmd)

好了,這篇文章的內(nèi)容到這就基本結(jié)束了,大家都學(xué)會(huì)了嗎?希望對(duì)大家的學(xué)習(xí)和工作能有一定的幫助。

相關(guān)文章

最新評(píng)論