import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
from collections import namedtuple
import enum
images = {
'num': 3,
'path_file': ''
}
def image_handle():
def show_pic(file_path):
pic = tk.Tk()
pic_image = Image.open(file_path)
w = pic_image.size[0]
h = pic_image.size[1]
pic_size = str(str(w) + 'x' + str(h))
window.geometry(pic_size)
pic_tkimage = ImageTk.PhotoImage(pic_image)
pic_label = tk.Label(image = pic_tkimage)
pic_label.pack()
pic.mainloop()
def cut(name1,d):
name1 = name1
print(name1)
img = Image.open(name1)
d = d
w = img.size[0]
h = img.size[1]
vx = int(w/d)
vy = int(h/d)
print(name1)
print(d)
n1 = 1
n2 = 1
# print(w,h)
# print(vx, vy)
x1 = 0
y1 = 0
c = 1
while n2<(d+1):
while n1<(d+1):
a = n2*vx
b = n1*vy
name2 = '/home/zhang/Desktop/pic/测试/' + name1.split('.')[0].split('/')[-1] + '_' + str(c) + '.' + name1.split('.')[1]
img_q = img.crop((x1,y1,a,b))
img_q.save(name2)
print(c)
y1 = n1*vy
n1 += 1
c += 1
n1 = 1
x1 = n2*vx
y1 = 0
n2 += 1
messagebox.showinfo('提示','图片切割完成')
def open_pic():
file_path = filedialog.askopenfilename()
if file_path:
images['path_file'] = file_path
suffix = file_path.split('.')[1]
if suffix in suffixs:
show_pic(file_path)
else:
messagebox.showwarning('警告','请选择图片文件')
else:
messagebox.showwarning('友情提示','文件路径错误')
def handle_pic():
cut(images['path_file'], images['num'])
def catch():
num = int(pic_radio.get())
images['num'] = num
# print(d)
suffixs = ['png','jpg','jpeg']
window = tk.Tk()
window.title('图片处理')
# window.geometry('300x200')
# var = tk.StringVar()
pic_radio = tk.IntVar()
radio1 = tk.Radiobutton(window, text='四宫格', value = 2,variable = pic_radio,command = catch)
radio1.pack()
radio2 = tk.Radiobutton(window,text ='九宫格', value=3,variable = pic_radio,command = catch)
radio2.pack()
radio3 = tk.Radiobutton(window, text='十六宫格',value=4,variable=pic_radio,command = catch)
radio3.pack()
open_file = tk.Button(text='打开图片', width=30, command = open_pic)
open_file.pack()
handle_pic = tk.Button(text='切割图片', width=30,command=handle_pic)
handle_pic.pack()
# l = tk.Label(textvar = var, bg = 'blue', width=20, )
# l.pack()
# bon = False
# window.withdraw()
# b = tk.Button(text = '点我有惊喜', width = 20, command = hit)
# b.pack()
window.mainloop()
if __name__ == '__main__':
image_handle()
来源:CSDN
作者:扣剑书生
链接:https://blog.csdn.net/weixin_44038167/article/details/103692706