實現效果
將位于/img目錄下的1000張.png圖片,轉換成.webp格式,并存放于img_webp文件夾內。

源圖片目錄

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