原文在我的博客:Python實現將webp格式的圖片轉化成jpg/png
轉換需要使用Pillow
這個庫:
pip install Pillow
代碼如下:
from PIL import image
im = Image.open(input_image).convert("RGB")
im.save("test.jpg", "jpeg")
以上代碼參考了文章:Image Conversion (JPG ⇄ PNG/JPG ⇄ WEBP) with Python
下面這個代碼提供了更加完整的功能,包括支持輸入圖片的url以完成自動下載和格式轉換:
#!/usr/bin/env python3
import argparse
import urllib.request
from PIL import Image
def download_image(url):
path, _ = urllib.request.urlretrieve(url)
print(path)
return path
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('input_file', help="輸入文件")
parser.add_argument('output_file', help="輸出文件", nargs="?")
opt = parser.parse_args()
input_file = opt.input_file
if input_file.startswith("http"):
if opt.output_file is None:
print("輸入是URL時必須制定輸出文件")
input_file = download_image(input_file)
elif not input_file.endswith(".webp"):
print("輸入文件不是webp格式的")
exit()
filename = ".".join(input_file.split(".")[0:-1])
output_file = opt.output_file or ("%s.jpg" % filename)
im = Image.open(input_file).convert("RGB")
im.save(output_file, "jpeg")
urllib.request.urlcleanup()
將文件保存爲webp2jpg
並將其路徑加入PATH
環境變量,那麼就可以以如下方式使用這個腳本:
webp2jpg input.webp output.jpg
# 下面這個命令的輸出文件是input.jpg
webp2jpg input.webp
webp2jpg http://host.com/file.webp local_save.jpg