I try to put a image label on tkinter window, I add the functionality of grow and shrink the image and move the image on the main tkinter window
But as I click grow button, it increases size but got blurred and vice versa for shrink button
Here is my code, tell me where i am wrong?
from tkinter import*
from PIL import Image,ImageTk
from tkinter import Tk, Label, Button
from tkinter.filedialog import askopenfilename
import tkinter as tk
root = Tk()
root.title("image edit")
root.geometry('1000x600+500+100')
root.resizable(False,False)
#take image file from the system
Tk().withdraw()
filepath = askopenfilename()
img = Image.open(filepath)
tk_im = ImageTk.PhotoImage(img)
xi=100
yi=100
wi=100
hi=100
#function to increase size of label
def grow():
global img
global my_label
global xi
global yi
global wi
global hi
i=0
while i<2:
img = img.resize((xi, yi))
tk_im=ImageTk.PhotoImage(img)
my_label.configure(width=wi,
height=hi,image=tk_im)
my_label.image=tk_im
xi+=1
yi+=1
i+=1
wi+=1
hi+=1
#function to decrease size of image
def shrink():
global my_label
global img
global xi
global yi
global wi
global hi
i=0
while i<2:
img = img.resize((xi, yi))
tk_im=ImageTk.PhotoImage(img)
my_label.configure(width=wi,
height=hi,image=tk_im)
my_label.image=tk_im
xi-=1
yi-=1
i+=1
wi-=1
hi-=1
set image in label
my_label=Label(root,image=tk_im)
my_label.image=tk_im
my_label.pack()
buttons to resize image
grow_button=Button(root,text=
"grow",command=grow)
grow_button.pack()
shrink_button=Button(root,text=
"shrink",command=shrink)
shrink_button.pack()
root.mainloop()
your code is not exactly 'wrong' as people have different levels of quality they expect. if you want to be able to set your quality yourself however i would suggest resizing with Nearest Neighbour resampling so you don't introduce any new, blurred colours - just ones already existing in your image:
import numpy as np
from PIL import Image
im = Image.open("ImageTK").convert('RGB')
im = im.resize((200,200),resample=Image.NEAREST)
im.save("result.png")
You can go from a Pillow image to a numpy array with:
numpy_array = np.array(pillowImage)
and from numpy
array to a Pillow image with:
pillow_image = Image.fromarray(numpyArray)
You could also use PIL.Image/openCV and PIL.ImageFilter modules:
from PIL import Image, ImageFilter
import cv2
image = cv2.resize(image, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
image = Image.fromarray(image)
Here, fx
and fy
are the values you have to set yourself.
You should not modify the original image because its quality may be changed especially after shrinking. Save the resized image into another image as below:
resized_img = img.resize((xi, yi)) # don't modify the original image
tk_im = ImageTk.PhotoImage(resized_img)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.