How to resize an image using Tkinter?

TkinterServer Side ProgrammingProgramming

To process images with Tkinter and other Python packages, we generally use the Pillow Package (or PIL) in Python. It provides a way to load, process, manipulate, convert, and helps to resize the images. The package can be installed by using the command pip install Pillow. Once the package is installed, we can import it using the ‘from PIL import Image, ImageTk’ command.

To resize an image using the PIL package, we have to follow these steps −

• Install Pillow Package or PIL in the local machine.

• Open the Image using Open(image_location) method.

• Resize the given image using resize((w,h), Image. ANTIALIAS) method where ANTIALIAS removes the structural Padding from the Image around it.

• Display the Image using Canvas create_image(x,y, image) method.

Example

#Import the required Libraries
from tkinter import *
from PIL import Image,ImageTk

#Create an instance of tkinter frame
win = Tk()

#Set the geometry of tkinter frame
win.geometry("750x270")

#Create a canvas
canvas= Canvas(win, width= 600, height= 400)
canvas.pack()

#Load an image in the script

#Resize the Image using resize method
resized_image= img.resize((300,205), Image.ANTIALIAS)
new_image= ImageTk.PhotoImage(resized_image)

#Add image to the Canvas Items
canvas.create_image(10,10, anchor=NW, image=new_image)

win.mainloop()

Output

Running the above code will display a window that will display a resized image in the Canvas.

Published on 03-May-2021 11:17:57