Image resize under PhotoImage

Viewed 117748

I need to resize an image, but I want to avoid PIL, since I cannot make it work under OS X - don't ask me why...

Anyway since I am satisfied with gif/pgm/ppm, the PhotoImage class is ok for me:

photoImg = PhotoImage(file=imgfn)
images.append(photoImg)
text.image_create(INSERT, image=photoImg)

The problem is - how do I resize the image? The following works only with PIL, which is the non-PIL equivalent?

img = Image.open(imgfn)
img = img.resize((w,h), Image.ANTIALIAS)
photoImg = ImageTk.PhotoImage(img)
images.append(photoImg)
text.image_create(INSERT, image=photoImg) 

Thank you!

5 Answers

If you don't have PIL installed --> install it

(for Python3+ users --> use 'pip install pillow' in cmd)

from tkinter import *
import tkinter
import tkinter.messagebox
from PIL import Image
from PIL import ImageTk

master = Tk()
 
def callback():
    print("click!")

width = 50
height = 50
img = Image.open("dir.png")
img = img.resize((width,height), Image.ANTIALIAS)
photoImg =  ImageTk.PhotoImage(img)
b = Button(master,image=photoImg, command=callback, width=50)
b.pack()
mainloop()

I had a requirement where I wanted to open an image, resize it, keeping the aspect ratio, save it under a new name, & display it in a tkinter window (using Linux Mint). After looking through dozens of forum questions, and dealing with some weird errors (semmingly involving the PIL to Pillow fork in Python 3.x), I was able to develop some code that works, using a predefined new maximum width or new maximum height (scaling up or down as necessary), and a Canvas object, where the image is displayed centered in the frame. Note that I did not include the file dialogs, just a hardcoded Image open & save for one file:

from tkinter import *
from PIL import ImageTk, Image
import shutil,os
from tkinter import filedialog as fd

maxwidth = 600
maxheight = 600

mainwindow = Tk()
picframe = Frame(mainwindow)
picframe.pack()
canvas = Canvas(picframe, width = maxwidth, height = maxheight)  
canvas.pack()

img = Image.open("/home/user1/Pictures/abc.jpg")

width, height = img.size                # Code to scale up or down as necessary to a given max height or width but keeping aspect ratio
if width > height:
    scalingfactor = maxwidth/width
    width = maxwidth
    height = int(height*scalingfactor)
else:
    scalingfactor = maxheight/height
    height = maxheight
    width = int(width*scalingfactor)

img = img.resize((width,height), Image.ANTIALIAS)

img.save("/home/user1/Pictures/Newabc.jpg")

img = ImageTk.PhotoImage(img)     # Has to be after the resize
canvas.create_image(int(maxwidth/2)-int(width/2), int(maxheight/2)-int(height/2), anchor=NW, image=img)   # No autocentering in frame, have to manually calculate with a new x, y coordinate based on a NW anchor (upper left)
Related