侧边栏壁纸
博主头像
YOUZI

我依旧在追寻自由的路上

  • 累计撰写 85 篇文章
  • 累计创建 10 个分类
  • 累计创建 27 个标签

目 录CONTENT

文章目录

使用文件管理器选择图片转webp

柚子
原创 / 2024-08-31 / 0 评论 / 2 点赞 / 15 阅读 / 0 字
温馨提示:
部分素材来自网络,若不小心影响您的利益,请联系 站长 删除。

前言

觉得之前的(图片批量转webp)不太好用,过于繁琐,于是给更新了一下。

代码

from PIL import Image
import os
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from tkinter import Tk, filedialog, messagebox

# 记录开始时间,用于计算过程耗时
start_time = time.time()

def select_images():
    """打开文件管理器选择图片"""
    Tk().withdraw()  # 隐藏主窗口
    file_paths = filedialog.askopenfilenames(title="选择图片文件", filetypes=[("Image Files", "*.jpg;*.jpeg;*.png;*.bmp;*.gif;*.webp")])
    return list(file_paths)

def convert_image(img_path, output_dir, format_type):
    """将图像转换为指定格式并保存到输出目录"""
    # 提取文件名
    filename = os.path.basename(img_path)
    # 生成转换后的文件名
    output_filename = os.path.splitext(filename)[0] + format_type['extension']
    # 生成输出路径
    output_path = os.path.join(output_dir, output_filename)

    # 打开图像文件
    img = Image.open(img_path)
    # 保存图像为指定格式
    img.save(output_path, format_type['format'], **format_type.get('options', {}))

def convert_images(image_paths, output_dir, modes=None):
    """批量转换图像格式"""
    # 默认转换模式为webp
    if modes is None:
        modes = ["webp"]

    # 如果输出目录不存在,则创建它
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 总文件数
    total_files = len(image_paths)

    # 定义支持的格式及其选项
    format_options = {
        'webp': {'format': 'webp', 'extension': '.webp'},
    }

    # 使用线程池执行转换任务
    converted_count = 0
    with ThreadPoolExecutor() as executor:
        futures = []
        for img_path in image_paths:
            for mode in modes:
                if mode in format_options:
                    futures.append(executor.submit(convert_image, img_path, output_dir, format_options[mode]))

        for _ in as_completed(futures):
            converted_count += 1
            print(f"转换进度: {converted_count}/{total_files}")

    # 计算并打印转换耗时
    elapsed_time = time.time() - start_time
    print(f"转换完成,总耗时: {elapsed_time:.2f} 秒")

    # 转换完成后,显示提示消息框
    Tk().withdraw()  # 隐藏主窗口
    messagebox.showinfo("完成", f"图像转换完成,总耗时: {elapsed_time:.2f} 秒")


if __name__ == "__main__":
    # 选择图片
    selected_images = select_images()
    if selected_images:
        output_directory = filedialog.askdirectory(title="选择输出目录")
        convert_images(selected_images, output_directory)
    else:
        print("未选择任何图片。")

拓展

嫌麻烦可使用打包好的exe文件。

效果预览

2024-08-31-B61u.webp

2024-08-31-31DL.webp2024-08-31-AGla.webp

耗时是记录从窗口打开到转换完成的过程,不做参考,此窗口原意只是提示转换完成。

下载

2

评论区