Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image resize under PhotoImage

Tags:

python

tkinter

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!

like image 345
alessandro Avatar asked Jul 05 '11 12:07

alessandro


People also ask

How do I resize a photo in PhotoImage?

To resize the image, we can use image_resize((width, height) **options) method. The resized image can later be processed and displayed through the label widget.

How do I resize an image in a dataset in Python?

You can resize multiple images in Python with the awesome PIL library and a small help of the os (operating system) library. By using os. listdir() function you can read all the file names in a directory. After that, all you have to do is to create a for loop to open, resize and save each image in the directory.


2 Answers

Because both zoom() and subsample() want integer as parameters, I used both.

I had to resize 320x320 image to 250x250, I ended up with

imgpath = '/path/to/img.png' img = PhotoImage(file=imgpath) img = img.zoom(25) #with 250, I ended up running out of memory img = img.subsample(32) #mechanically, here it is adjusted to 32 instead of 320 panel = Label(root, image = img) 
like image 81
Memes Avatar answered Sep 17 '22 14:09

Memes


You have to either use the subsample() or the zoom() methods of the PhotoImage class. For the first option you first have to calculate the scale factors, simply explained in the following lines:

scale_w = new_width/old_width scale_h = new_height/old_height photoImg.zoom(scale_w, scale_h) 
like image 27
Constantinius Avatar answered Sep 20 '22 14:09

Constantinius