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

源圖片目錄

目標(biāo)圖片目錄
關(guān)于批量生成1000張圖片,可以參考這篇文章:利用Python批量生成任意尺寸的圖片
實(shí)現(xiàn)示例
import globimport osimport threadingfrom PIL import Imagedef 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 += 1if __name__ == "__main__": start()注意:該項(xiàng)目需要引用PIL庫。
考慮到是大量的線性密集型運(yùn)算,因此使用了多線程并發(fā)。通過threading.Thread()創(chuàng)建線程對象時(shí)注意,args參數(shù)僅接受元祖。
在這里,我們使用Image.open()函數(shù)打開圖像。
最終調(diào)用save("img_webp/webp_" + str(index) + ".webp", "WEBP")方法,以指定格式寫入指定位置。其中format參數(shù)為目標(biāo)格式。
好了,這篇文章的內(nèi)容到這就基本結(jié)束了,大家都學(xué)會(huì)了嗎?希望對大家的學(xué)習(xí)和工作能有一定的幫助。
新聞熱點(diǎn)
疑難解答
圖片精選