抖音玩家的实用工具:图片的分割代码
from tkinter import Tk, Button, filedialog
from PIL import Image
def split_image(image_path, rows, cols):
image = Image.open(image_path)
width, height = image.size
cell_width = width // cols
cell_height = height // rows
cells = []
for i in range(rows):
for j in range(cols):
left = j * cell_width
top = i * cell_height
right = left + cell_width
bottom = top + cell_height
cell = image.crop((left, top, right, bottom))
cells.append(cell)
return cells
def select_image():
image_path = filedialog.askopenfilename(filetypes=(("Image files", "*.jpg; *.png"), ("All files", "*.*")))
if image_path:
rows = 6 # 分割行数
cols = 3 # 分割列数
cells = split_image(image_path, rows, cols)
folder_path = filedialog.askdirectory() # 选择保存文件夹
if folder_path: # 如果选择了文件夹则保存图片
for i, cell in enumerate(cells):
cell.save(f'{folder_path}/cell_{i}.jpg') # 将每个小等分保存为单独的图片
# 创建窗口
window = Tk()
window.title("图片分割程序")
window.geometry("200x100")
# 创建选择图片按钮
button = Button(window, text="选择图片", command=select_image)
button.pack(pady=20)
# 运行窗口主循环
window.mainloop()
|