from
PIL
import
Image
import
tkinter as tk
from
tkinter
import
filedialog
import
os
from
datetime
import
datetime
def
crop_images():
root
=
tk.Tk()
root.withdraw()
file_paths
=
filedialog.askopenfilenames(filetypes
=
[(
"Image files"
,
"*.png;*.jpg;*.jpeg"
)])
if
file_paths:
output_root_folder
=
filedialog.askdirectory()
if
output_root_folder:
current_time
=
datetime.now().strftime(
"%Y%m%d%H%M%S"
)
new_folder_name
=
f
"{current_time}ki裁剪800"
new_folder_path
=
os.path.join(output_root_folder, new_folder_name)
if
not
os.path.exists(new_folder_path):
os.makedirs(new_folder_path)
for
file_path
in
file_paths:
try
:
image
=
Image.
open
(file_path)
width, height
=
image.size
if
width <
800
or
height <
800
:
crop_size
=
min
(width, height)
else
:
crop_size
=
800
left
=
(width
-
crop_size)
/
/
2
top
=
(height
-
crop_size)
/
/
2
right
=
left
+
crop_size
bottom
=
top
+
crop_size
cropped_image
=
image.crop((left, top, right, bottom))
file_name
=
file_path.split(
"/"
)[
-
1
]
output_name
=
file_name.rsplit(
'.'
,
1
)[
0
]
+
'_cropped.'
+
file_name.rsplit(
'.'
,
1
)[
1
]
output_path
=
os.path.join(new_folder_path, output_name)
cropped_image.save(output_path)
print
(f
"裁剪并保存图片: {output_path}"
)
except
Exception as e:
print
(f
"处理图片 {file_path} 时出错: {e}"
)
if
__name__
=
=
"__main__"
:
crop_images()