侧边栏壁纸
博主头像
YOUZI

我依旧在追寻自由的路上

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

目 录CONTENT

文章目录

图片批量命名+webp转换

柚子
原创 / 2024-07-15 / 0 评论 / 0 点赞 / 17 阅读 / 0 字
温馨提示:
本文最后更新于66天前,若内容或图片失效,请留言反馈。 部分素材来自网络,若不小心影响您的利益,请联系 站长 删除。

代码

带前缀

from PIL import Image
import os


def rename_files(target_directory, file_prefix):
    # 遍历文件夹中的文件
    files = os.listdir(target_directory)
    files.sort()  # 按字母顺序排序文件

    renamed_files = []

    # 重命名文件
    for i, file in enumerate(files, start=1):
        if file.lower().endswith(('.jpg', '.png', '.jpeg')):
            old_path = os.path.join(target_directory, file)
            new_filename = f'{file_prefix}{str(i).zfill(3)}{os.path.splitext(file)[1]}'
            new_path = os.path.join(target_directory, new_filename)

            # 如果新命名文件已存在则跳过
            if os.path.exists(new_path):
                print(f'命名文件已存在,跳过: {new_filename}')
                renamed_files.append(new_filename)
                continue

            os.rename(old_path, new_path)
            print(f'已重命名: {file} -> {new_filename}')
            renamed_files.append(new_filename)
        else:
            print(f'跳过非图片文件: {file}')

    print("图片文件已按照数字升序重命名。")
    return renamed_files


def convert_images_to_webp(source_dir, output_dir, files):
    # 创建输出目录(如果不存在)
    if not os.path.exists(output_dir):
        print("目录不存在,正在创建目录!")
        os.makedirs(output_dir)
        print("创建目录成功!")

    # 遍历指定的文件
    for filename in files:
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            img_path = os.path.join(source_dir, filename)
            if not os.path.exists(img_path):
                print(f'文件不存在,跳过: {filename}')
                continue

            img = Image.open(img_path)

            # 转换为webp格式
            webp_filename = os.path.splitext(filename)[0] + '.webp'
            webp_path = os.path.join(output_dir, webp_filename)
            img.save(webp_path, 'webp')

            print(f"已转换: {filename} -> {webp_filename}")

    print("转换完成!")


# 设置路径和前缀
source_directory = r'D:\Pictures\搜图神器'
output_directory = r'E:\webp\搜图神器'
prefix = 'soutu-'

# 先重命名文件
renamed_files = rename_files(source_directory, prefix)

# 再转换文件格式
convert_images_to_webp(source_directory, output_directory, renamed_files)

不带前缀

from PIL import Image
import os


def rename_files(target_directory):
    # 获取目录下所有文件
    files = os.listdir(target_directory)

    # 过滤出所有图片文件
    image_files = [file for file in files if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))]

    # 按照数字升序重命名图片文件
    renamed_files = []
    for i, file in enumerate(sorted(image_files), 1):
        # 构造新文件名
        _, ext = os.path.splitext(file)
        new_name = f"{i:03d}{ext}"

        # 检查新文件名是否已经存在
        if os.path.exists(os.path.join(target_directory, new_name)):
            print(f'命名文件已存在,跳过: {new_name}')
            renamed_files.append(new_name)
            continue

        # 重命名文件
        os.rename(os.path.join(target_directory, file), os.path.join(target_directory, new_name))
        print(f'已重命名: {file} -> {new_name}')
        renamed_files.append(new_name)

    print("图片文件已按照数字升序重命名。")
    return renamed_files


def convert_images_to_webp(source_dir, output_dir, files):
    # 创建输出目录(如果不存在)
    if not os.path.exists(output_dir):
        print("目录不存在!")
        os.makedirs(output_dir)
        print("创建目录成功!")

    # 遍历指定的文件
    for filename in files:
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            # 打开图片
            img_path = os.path.join(source_dir, filename)
            img = Image.open(img_path)

            # 转换为webp格式
            webp_filename = os.path.splitext(filename)[0] + '.webp'
            webp_path = os.path.join(output_dir, webp_filename)
            img.save(webp_path, 'webp')

            print(f"Converted {filename} to {webp_filename}")

    print("转换完成!")


# 设置路径和前缀
source_directory = r'D:\Pictures\流萤'
output_directory = r'D:\Pictures\流萤-webp'

# 先重命名文件
renamed_files = rename_files(source_directory)

# 再转换文件格式
convert_images_to_webp(source_directory, output_directory, renamed_files)

0

评论区