【问题标题】:Converting all images in a folder to .webp using python script使用python脚本将文件夹中的所有图像转换为.webp
【发布时间】:2019-08-24 02:02:38
【问题描述】:

我一直在为网站处理图片,发现.webp 格式比.jpeg.png 更紧凑,在Docs 上查找更多信息。

现在我有一个包含近 25 张图片的文件夹,我想将所有图片转换为 .webp 格式。谁能建议我如何在不使用在线工具的情况下仅使用 python 脚本进行转换。

【问题讨论】:

    标签: python html python-3.x webp


    【解决方案1】:

    首先你必须根据你的机器(Windows|Linux)从here下载cwebp压缩工具。

    现在提取C:\Program Files\中的文件夹后,您必须将set path转换为cwebp.exe,下面是我的路径 Path:: C:\Program Files\libwebp\bin

    打开 cmd 看看你现在是否已经完成了。

    • cmd> cwebp -version

    • cmd> python --version

    现在超级简单,只需运行下面的脚本,你就会得到你想要的输出,或者你可以从here下载我在 github 上的 repo

    # --cwebp_compressor.py--
    
    # cmd> python cwebp_compressor.py folder-name 80
    
    import sys
    from subprocess import call
    from glob import glob
    
    #folder-name
    path = sys.argv[1]
    #quality of produced .webp images [0-100]
    quality = sys.argv[2]
    
    if int(quality) < 0 or int(quality) > 100:
        print("image quality out of range[0-100] ;/:/")
        sys.exit(0)
    
    img_list = []
    for img_name in glob(path+'/*'):
        # one can use more image types(bmp,tiff,gif)
        if img_name.endswith(".jpg") or img_name.endswith(".png") or img_name.endswith(".jpeg"):
            # extract images name(image_name.[jpg|png]) from the full path
            img_list.append(img_name.split('\\')[-1])
    
    
    # print(img_list)   # for debug
    for img_name in img_list:
        # though the chances are very less but be very careful when modifying the below code
        cmd='cwebp \"'+path+'/'+img_name+'\" -q '+quality+' -o \"'+path+'/'+(img_name.split('.')[0])+'.webp\"'
        # running the above command
        call(cmd, shell=False)  
        # print(cmd)    # for debug
    

    【讨论】:

    • 为什么不同时使用 -near_lossless 80 和有损的,然后取较小的?
    • @JyrkiAlakuijala 很好,当我开始使用 webp 转换时,我发现将所有 25 张图像一张一张地转换很麻烦……上面的代码更多地是关于批量图像的转换…… .嗯,你可以在你的代码中做到这一点......好主意
    • 我不得不将call(cmd, shell=False) 更改为call(cmd, shell=True),因为我们正在传递一个shell 命令。 reference.
    • 谢谢!我根据需要对其进行了修改(与 shell 一起使用,将文件保存在单独的文件夹中)。效果很好!我的版本:gist.github.com/apiwonska/d2a0938fc68909e14f83876e72a55325
    猜你喜欢
    • 2019-11-18
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 2016-01-22
    • 2013-11-20
    • 2021-09-18
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多