自动把图片裁剪正方形工具(两边补白)

自动把图片裁剪正方形工具(两边补白)

自动把图片裁剪正方形工具(两边补白)

自动把图片裁剪正方形工具(两边补白)

代码如下:

import os
from PIL import Image
import tkinter as tk
from tkinter import filedialog
from tkinterdnd2 import DND_FILES, TkinterDnD

def is_valid_image(file_path):
    if not os.path.isfile(file_path):
        return False
    extension = os.path.splitext(file_path)[1].lower()
    if extension not in ['.jpg', '.jpeg', '.png']:
        return False
    try:
        with open(file_path, 'rb') as f:
            img = Image.open(f)
            img.verify()
        return True
    except (OSError, IOError) as e:
        return False

def process_image(image_path):
    if is_valid_image(image_path):
        img = Image.open(image_path)
        width, height = img.size
        target_size = max(width, height)
        new_img = Image.new('RGB', (target_size, target_size), (255, 255, 255))
        if width > height:
            padding = (target_size - height) // 2
            new_img.paste(img, (0, padding))
        else:
            padding = (target_size - width) // 2
            new_img.paste(img, (padding, 0))
        new_img.save(image_path)
        print(f"已处理图片:{image_path}")
    else:
        print("拖入的不是有效的图片文件。")

def on_drop(event):
    file_path = event.data
    print(f"Received file path: {file_path}")
    if isinstance(file_path, str):
        process_image(file_path)
    else:
        for path in file_path:
            process_image(path)

root = TkinterDnD.Tk()
root.title("图片处理工具")

label = tk.Label(root, text="将图片拖放到此处")
label.pack(padx=20, pady=20)

root.drop_target_register(DND_FILES)
root.dnd_bind('<<Drop>>', on_drop)

root.mainloop()

只需拖进图片就可以自动秒裁剪,注意路径不能带中文

同时做了打包,方便没环境的电脑直接用:

通过度网盘分享的文件:build.zip 链接:
https://pan.baidu.com/s/1fhPu03vMl3s0tyROWJjtTA 提取码:vn29

通过蓝奏盘分享的文件:build.zip 链接:

https://wwuu.lanzouo.com/iG4iU2dihpof

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 共29条

请登录后发表评论