[英]"copy and paste" python program
我目前正在嘗試編寫一個程序來讀取 GIF 文件,在屏幕上顯示其圖像,然后允許用戶選擇圖像的矩形部分進行“復制和粘貼”,也就是在矩形內復制圖像然后將結果另存為新的 GIF 文件。 我已經走得很遠了,但是每次我想我已經弄清楚時,似乎都會彈出一個新錯誤!
# CopyAndPaste.py
# This program is designed to read a GIF file, display its image on the screen, allows the user to
# select a rectangular portion of the image to copy and paste, and then save the result as a new GIF file
import tkinter
from tkinter import *
import base64
root = Tk()
def action(canvas):
canvas.bind("<Button-1>", xaxis)
canvas.bind("<ButtonRelease-1>", yaxis)
canvas.bind("<ButtonRelease-1>", box)
def xaxis(event):
global x1, y1
x1, y1 = (event.x - 1), (event.y - 1)
print (x1, y1)
def yaxis(event):
global x2, y2
x2, y2 = (event.x + 1), (event.y + 1)
print (x2, y2)
def box(event):
photo = PhotoImage(file="picture.gif")
yaxis(event)
canvas.create_rectangle(x1,y1,x2,y2)
for x in range(x1, x2):
for y in range(y1, y2):
r,g,b = getRGB(photo, x, y)
newImage(r, g, b, x, y)
def getRGB(photo, x, y):
value = photo.get(x, y)
return tuple(map(int, value.split(" ")))
def newImage(r, g, b, x, y):
picture = PhotoImage(width=x, height=y)
picture.put("#%02x%02x%02x" % (r,g,b), (x,y))
picture.write('new_image.gif', format='gif')
canvas = Canvas(width=500, height=250)
canvas.pack(expand=YES, fill=BOTH)
photo = PhotoImage(file="picture.gif")
canvas.create_image(0, 0, image=photo, anchor=NW)
canvas.config(cursor='cross')
action(canvas)
root.mainloop()
您的代碼的主要問題是您為每個像素創建了一個新的PhotoImage
! 相反,只需創建一次PhotoImage
並在雙for
循環中添加像素。
def box(event):
yaxis(event)
canvas.create_rectangle(x1, y1, x2, y2)
picture = PhotoImage(width=(x2-x1), height=(y2-y1))
for x in range(x1, x2):
for y in range(y1, y2):
r, g, b = photo.get(x, y)
picture.put("#%02x%02x%02x" % (r, g, b), (x-x1, y-y1))
picture.write('new_image.gif', format='gif')
此外,您的getRGB
函數中的tuple(map(int, value.split(" ")))
行是錯誤的,因為value
已經是您要創建的元組,而不是字符串。 1)如您所見,我只是將該部分直接“內聯”到box
函數中。 另一個問題是您將復制的像素寫入x
和y
,但您必須將它們寫入x-x1
和y-y1
。
更新 1: 1)看起來PhotoImage.get
的返回值取決於您使用的 Python/Tkinter 版本。 在某些版本中,它返回一個元組,例如(41, 68, 151)
,而在其他版本中,它返回一個字符串,例如u'41 68 151'
。
更新 2:正如@Oblivion 所指出的,您實際上可以只使用PhotoImage.write
的from_coords
參數來指定要保存到文件的圖片區域。 有了這個, box
函數可以簡化為
def box(event):
yaxis(event)
canvas.create_rectangle(x1, y1, x2, y2)
photo.write('new_image.gif', format='gif', from_coords=[x1, y1, x2, y2])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.