返回
Featured image of post 使用python制作的目录图片转换神器

使用python制作的目录图片转换神器

不需要额外的安装即可实现程序所在目录的全部图片转换

目录

TL;DR / 极客简报:

  • 基于 Python Pillowtqdm 库实现的递归式目录图片批量转换脚本。
  • 支持 WebP 转 JPG 以及多格式转 WebP 的双向逻辑,主打高效压缩。
  • 免安装独立运行设计,完美兼容 Win7 及以上的老旧或现代 Windows 环境。

# 说明

本程序是一个用于转换程序所在的文件夹包括子文件夹全部图片的程序,本程序兼容win7以上的运行

# 实际运行效果

效果

# Src

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import os
import sys
import time
from PIL import Image
from tqdm import tqdm


def convert_to_webp(input_file, output_file, quality=80):
    try:
        with Image.open(input_file) as im:
            im.save(output_file, "webp", quality=quality)
        print(f"Converted: {input_file} => {output_file}")
    except Exception as e:
        print(f"Error converting file: {input_file}")
        print(str(e))


def convert_to_jpg(input_file, output_file):
    try:
        with Image.open(input_file) as im:
            im.save(output_file, "JPEG")
        print(f"Converted: {input_file} => {output_file}")
    except Exception as e:
        print(f"Error converting file: {input_file}")
        print(str(e))


def process_folder(folder_path, conversion_type):
    for root, dirs, files in os.walk(folder_path):
        for filename in tqdm(files):
            if conversion_type == 1 and filename.lower().endswith('.webp'):
                input_file = os.path.join(root, filename)
                output_file = os.path.splitext(input_file)[0] + ".jpg"
                convert_to_jpg(input_file, output_file)
            elif conversion_type == 2 and any(
                    filename.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.webp', '.jpeg']):
                input_file = os.path.join(root, filename)
                output_file = os.path.splitext(input_file)[0] + ".webp"
                convert_to_webp(input_file, output_file)


if __name__ == "__main__":
    print("LEl_FENG xpdbk.com 图片批量处理是否继续?[Enter继续]")
    input()
    print("webp转换jpg[1]\npng和jpg转换[2]\n想要转换请输入1或者2")
    conversion_type = int(input())
    print("请您一定要知道本程序是转换程序所在的文件夹里面的所有图片所以请您一定要小心[Enter继续]")
    input()
    folder_path = os.path.dirname(sys.argv[0])
    process_folder(folder_path, conversion_type)
    print("转换完成,程序将在5秒后自动退出。")
    time.sleep(5)