51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

python批量图片转webp格式

前言 {#前言}

这段时间,想着把以后在博客网站上的图片都换成webp,压缩加,加载也能快一点。但是不知道有什么好的工具批量生成。

最后搜了一下,发现python是有库的,那就很简单了,接下来直接看代码。

正文 {#正文}

import os
from PIL import Image

def convert_images_to_webp(input_folder, output_folder, quality=80):
"""
Convert all non-WebP images in the input_folder to WebP format and save them to output_folder.
Existing WebP images are skipped.


    Args:
    - input_folder (str): The folder containing images to convert.
    - output_folder (str): The folder where converted WebP images will be saved.
    - quality (int): The quality of the converted WebP images, default is 80.
    """

    # Check if output folder exists, if not, create it
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # Iterate over all files in the input folder
    for filename in os.listdir(input_folder):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
            # Construct the full file path
            file_path = os.path.join(input_folder, filename)
            # Open the image
            image = Image.open(file_path)
            # Convert and save the image in WebP format
            webp_filename = os.path.splitext(filename)[0] + '.webp'
            webp_path = os.path.join(output_folder, webp_filename)
            image.save(webp_path, 'webp', quality=quality)
            print(f"Saved {filename}")
        elif filename.lower().endswith('.webp'):
            webp_path = os.path.join(output_folder, filename)
            with open(file_path, 'rb') as file:
                with open(webp_path, 'wb') as output_file:
                    output_file.write(file.read())
            print(f"Skipping existing WebP file: {filename}")

    print(f"All non-WebP images from {input_folder} have been converted and saved to {output_folder}")




if name == 'main':
convert_images_to_webp('photos', 'photos/webp2')


注释都很清楚了,这里就说下重点。

主要流程就是将非webp的图片转换后丢到指定目录,已经是webp的就直接丢过去。

有三个参数,input_folder, output_folder, quality

input_folder

你要转换的图片文件夹

output_folder

转换后输出的路径

quality

图片压缩质量,默认80,一般也不用改。

要注意的是,权限要给够,不然可能复制失败。

效果如下: {#效果如下}

3dc4ed22c2dd0b340c793ea98de8b64c.webp

13793c0b4f7be2ea5ce5bb8346464c27.webp

9156025ca6b78df60b8fb50f4eac92ab.webp

赞(0)
未经允许不得转载:工具盒子 » python批量图片转webp格式