图片裁剪器
本帖最后由 wangzherongyao2 于 2024-3-11 15:12 编辑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 wazct 发表于 2024-3-10 22:01
求打包成程序
已经打包成exe文件 已测试!
1、打开exe程序后可以选择的不是文件夹 而是图片文件
2、选择图片后没有任何提示 任何选项 只能通过左键来框选截图区域 图片大小无法等比缩放处理 每次框选都只能框选人物的一半改变窗口也没办法完整显示图片
3、确定后只能裁切一张图片 跟文件夹内的其他图片没有任何关系 求打包成程序{:1_889:} 谢谢分享 好东西啊 求什么语言编的! 谢谢分享 这个有意思,感谢楼主分享 看不懂有没有程序呢 好多这类型的软件了,但还是感谢😊 跟着学习一下