【Python】裁切图片为指定画幅比例

该工具是在截取MTV的画面时产生的需求,一些4:3画幅的视频制作时候加入了黑边,成了16:9视频,因此想截图出原本4:3的画面,一方面可以进剪辑软件进行直接裁剪,也可以在原视频进行导出后操作,考虑到二压费时费力,因此选择对截取的图片进行批处理。

import os
import random
import string
from tkinter import Tk, filedialog, Button, Label, messagebox
from PIL import Image


def random_filename(extension):
    """生成随机文件名"""
    chars = string.ascii_letters + string.digits
    return ''.join(random.choices(chars, k=8)) + f".{extension}"


def crop_to_aspect(image, target_ratio=4/3):
    """裁剪图像宽边以符合指定宽高比"""
    width, height = image.size
    current_ratio = width / height

    if current_ratio > target_ratio:  # 如果宽高比大于目标比例,宽度过大
        new_width = int(height * target_ratio)  # 计算符合比例的新宽度
        left = (width - new_width) // 2  # 左侧裁剪量
        right = left + new_width  # 右侧裁剪量
        image = image.crop((left, 0, right, height))  # 裁剪左右宽边

    return image


def process_images():
    """处理图片并保存结果"""
    input_files = filedialog.askopenfilenames(
        title="选择图片文件",
        filetypes=[("Image Files", "*.jpg *.png")]
    )
    if not input_files:
        return

    output_dir = filedialog.askdirectory(title="选择输出文件夹")
    if not output_dir:
        return

    for file_path in input_files:
        try:
            with Image.open(file_path) as img:
                # 转换为符合比例的图片
                processed_img = crop_to_aspect(img)
                # 保存文件
                ext = file_path.split('.')[-1]
                output_path = os.path.join(output_dir, random_filename(ext))
                processed_img.save(output_path)
        except Exception as e:
            messagebox.showerror("错误", f"处理文件 {file_path} 时出错: {e}")
            continue

    messagebox.showinfo("完成", "图片批量处理完成!")


def create_gui():
    """创建GUI"""
    root = Tk()
    root.title("图片批量处理工具")
    root.geometry("400x200")

    Label(root, text="批量处理图片 - 保持高度裁切宽边为4:3比例").pack(pady=20)
    Button(root, text="选择图片并处理", command=process_images).pack(pady=10)
    Button(root, text="退出", command=root.quit).pack(pady=10)

    root.mainloop()


if __name__ == "__main__":
    create_gui()

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注