老K博客 - 一个源码和技术分享的博客

python批量图片转webp格式

老K博客
2024-11-06 / 0 评论 / 15 阅读 / 正在检测是否收录...
广告

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

有三个参数, input_folder , output_folder , quality

input_folder

你要转换的图片文件夹

output_folder

转换后输出的路径

quality

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

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

下面是代码

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')

效果

m35taemf.png
m35tah8b.png
m35tak7h.png

本文共 92 个字数,平均阅读时长 ≈ 1分钟
广告
0

海报

正在生成.....

评论 (0)

语录
取消
CC BY-NC-ND