Python基於tkinter canvas實現圖片裁剪功能
阿新 • • 發佈:2020-11-07
實現:tkinter 畫布上顯示圖片,按下滑鼠左鍵並且移動,實現截圖
程式碼如下
# -*- encoding=utf-8 -*- import os import tkinter as tk from PIL import Image from PIL import ImageTk left_mouse_down_x = 0 left_mouse_down_y = 0 left_mouse_up_x = 0 left_mouse_up_y = 0 sole_rectangle = None def left_mouse_down(event): # print('滑鼠左鍵按下') global left_mouse_down_x,left_mouse_down_y left_mouse_down_x = event.x left_mouse_down_y = event.y def left_mouse_up(event): # print('滑鼠左鍵釋放') global left_mouse_up_x,left_mouse_up_y left_mouse_up_x = event.x left_mouse_up_y = event.y corp_img(img_path,'img/one_corp.png',left_mouse_down_x,left_mouse_down_y,left_mouse_up_x,left_mouse_up_y) def moving_mouse(event): # print('滑鼠左鍵按下並移動') global sole_rectangle global left_mouse_down_x,left_mouse_down_y moving_mouse_x = event.x moving_mouse_y = event.y if sole_rectangle is not None: canvas.delete(sole_rectangle) # 刪除前一個矩形 sole_rectangle = canvas.create_rectangle(left_mouse_down_x,moving_mouse_x,moving_mouse_y,outline='red') def right_mouse_down(event): # print('滑鼠右鍵按下') pass def right_mouse_up(event): # print('滑鼠右鍵釋放') pass def corp_img(source_path,save_path,x_begin,y_begin,x_end,y_end): if x_begin < x_end: min_x = x_begin max_x = x_end else: min_x = x_end max_x = x_begin if y_begin < y_end: min_y = y_begin max_y = y_end else: min_y = y_end max_y = y_begin save_path = os.path.abspath(save_path) if os.path.isfile(source_path): corp_image = Image.open(source_path) region = corp_image.crop((min_x,min_y,max_x,max_y)) region.save(save_path) print('裁剪完成,保存於:{}'.format(save_path)) else: print('未找到檔案:{}'.format(source_path)) if __name__ == '__main__': pass win = tk.Tk() frame = tk.Frame() frame.pack() screenwidth = win.winfo_screenwidth() screenheight = win.winfo_screenheight() img_path = 'img/one.png' # img_path = 'img/bg.jpg' # img_path = 'img/test.jpg' # img_path = 'img/pic.gif' image = Image.open(img_path) image_x,image_y = image.size if image_x > screenwidth or image_y > screenheight: print('The picture size is too big,max should in:{}x{},your:{}x{}'.format(screenwidth,screenheight,image_x,image_y)) img = ImageTk.PhotoImage(image) canvas = tk.Canvas(frame,width=image_x,height=image_y,bg='pink') i = canvas.create_image(0,anchor='nw',image=img) canvas.pack() canvas.bind('<Button-1>',left_mouse_down) # 滑鼠左鍵按下 canvas.bind('<ButtonRelease-1>',left_mouse_up) # 滑鼠左鍵釋放 canvas.bind('<Button-3>',right_mouse_down) # 滑鼠右鍵按下 canvas.bind('<ButtonRelease-3>',right_mouse_up) # 滑鼠右鍵釋放 canvas.bind('<B1-Motion>',moving_mouse) # 滑鼠左鍵按下並移動 win.mainloop()
原圖one.png
執行
one_corp.png
原始碼(https://github.com/rainbow-tan/rainbow/tree/master/%E8%A3%81%E5%89%AA%E5%9B%BE%E7%89%87)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。