image - "copy and paste" python program -
i'm trying write program reads gif file, displays image on screen, allows user select rectangular portion of image "copy , paste", aka copy image within rectangle , save result new gif file. i've gotten pretty far it, every time think i've figured out seems new error pops up!
# copyandpaste.py # program designed read gif file, display image on screen, allows user # select rectangular portion of image copy , paste, , save result new gif file import tkinter 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) x in range(x1, x2): 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()
the main problem code create new photoimage
each pixel! instead, create photoimage
once , add pixels in double-for
-loop.
def box(event): yaxis(event) canvas.create_rectangle(x1, y1, x2, y2) picture = photoimage(width=(x2-x1), height=(y2-y1)) x in range(x1, x2): 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')
also, line tuple(map(int, value.split(" ")))
in getrgb
function wrong, value
tuple want create, not string.1) can see, 'inlined' part directly box
function. problem wrote copied pixels x
, y
, have write them x-x1
, y-y1
instead.
update 1: 1) seems return value of photoimage.get
depends on version of python/tkinter using. in versions, returns tuple, (41, 68, 151)
, , in others, string, u'41 68 151'
.
update 2: pointed out @oblivion, can in fact use from_coords
parameter of photoimage.write
specify region of picture saved file. this, box
function can simplified as
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])
Comments
Post a Comment