本帖最后由 wangzherongyao2 于 2024-3-11 15:12 编辑
[Asm] 纯文本查看 复制代码 from PIL import Image, ImageTk
import tkinter as tk
import imageio
class ImageCropper:
def __init__(self, image_path):
self.image = Image.open(image_path)
self.crop_coordinates = None
image = Image.open(image_path)
width, height = image.size
self.root = tk.Tk()
self.canvas_width = width # 设置画布宽度
self.canvas_height = height # 设置画布高度
self.canvas = tk.Canvas(self.root, width=self.canvas_width, height=self.canvas_height)
self.canvas.pack()
self.canvas.bind("<ButtonPress-1>", self.on_mouse_press)
self.canvas.bind("<B1-Motion>", self.on_mouse_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_mouse_release)
self.photo = ImageTk.PhotoImage(self.image.resize((self.canvas_width, self.canvas_height))) # 调整图片大小以适应画布
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)
self.root.mainloop()
def on_mouse_press(self, event):
self.start_x = event.x
self.start_y = event.y
def on_mouse_drag(self, event):
self.canvas.delete("crop_rectangle")
self.current_x = event.x
self.current_y = event.y
self.canvas.create_rectangle(self.start_x, self.start_y, self.current_x, self.current_y, outline="red", tags="crop_rectangle")
def on_mouse_release(self, event):
self.canvas.delete("crop_rectangle")
self.end_x = event.x
self.end_y = event.y
self.crop_coordinates = (min(self.start_x, self.end_x), min(self.start_y, self.end_y), max(self.start_x, self.end_x), max(self.start_y, self.end_y))
self.root.quit()
def open_image(self, root,path):
# file_path = filedialog.askopenfilename ()
open_image = imageio.imread(path)
image = Image. fromarray (open_image)
imgtk = ImageTk. PhotoImage (image=image)
panel = tk.Label(root)
panel.pack(padx=10,pady=10)
panel.imgtk = imgtk
panel.config (image=imgtk)
root.update()
# tkinter.messagebox.showinfo('图片地址: ',file_path)
# 图片路径
def 裁剪器(image_path = r"python\pic\2.png"):
# 替换为实际的图片路径
# 创建ImageCropper实例并获取裁剪区域坐标
cropper = ImageCropper(image_path)
crop_coordinates = cropper.crop_coordinates
# print("裁剪区域坐标:", crop_coordinates)
image = Image.open(image_path)
cropped_image = image.crop(crop_coordinates)
cropped_image.save(r"python\pic\1.no_bg.png")
if __name__ == '__main__':
裁剪器(image_path = r'python\pic\Demo.jpg')
重构后的代码和可执行文件:链接: https://pan.baidu.com/s/1NhA2e4qsMtEw0s2vykKg8A?pwd=8gkf 提取码: 8gkf |