首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python批量图片转webp格式

python批量图片转webp格式

作者头像
老K博客
发布2024-11-07 09:46:46
发布2024-11-07 09:46:46
33700
代码可运行
举报
文章被收录于专栏:老K博客老K博客
运行总次数:0
代码可运行

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

有三个参数, input_folder , output_folder , quality

input_folder

你要转换的图片文件夹

output_folder

转换后输出的路径

quality

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

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

下面是代码

代码语言:javascript
代码运行次数:0
运行
复制
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')

效果

m35tah8b.png
m35tah8b.png

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024年11月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • input_folder
  • output_folder
  • quality
  • 下面是代码
  • 效果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档