Python实现将webp格式的图片转化成jpg/png

原文在我的博客: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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章