0

Im currently using the code:

photo = Image.open('ImgSource').resize((x,y), Image.ANTIALIAS)
img = ImageTk.PhotoImage(photo)

where x and y are static dimensions, however my program uses multiple different image sizes and this code causes portrait rectangle images to appear stretched and squashed.

I have the image presented in a canvas as such:

canvas = tk.Canvas(self, background='grey')
canvas.grid(row=0, rowspan=2, column=1, columnspan=2, sticky=N+S+E+W)
...
canvas.create_image(150,150, image = img, anchor = 'center')

The remaining space in the grid/window is used by buttons.

Is there a way to perhaps scale down the image to fit inside the canvas/grid cell while still maintaining its original aspect ratio? I am very much a beginner at python so sorry if i've missed something or not given enough info.

Brady Gale
  • 33
  • 6
  • 1
    You are opening the image and immediately resizing it. If you do that in two statements, you can query its original width and height in between, and adjust `x` or `y` resizing to match. – Jongware Jan 29 '20 at 23:08
  • This sounds promising but what would be the query if i may ask? I was thinking i could do something like `.resize((ow*0.5, oh*0.5), image.ANTIALIAS)` where `ow` and `oh` are the original dimensions but I'm unsure on how to acquire them – Brady Gale Jan 29 '20 at 23:16
  • 1
    That's `[imageSizeWidth, imageSizeHeight] = image.size`. Dividing one by the other gives you the aspect. (Don't have tk installed so cannot write a valid answer...) – Jongware Jan 29 '20 at 23:25
  • Thank you for this! Would mark as answer if I could. I ended up using `pixels_x, pixels_y = tuple([int(x/6) for x in photo.size])` and `img = ImageTk.PhotoImage(photo.resize((pixels_x, pixels_y)))` to scale the image down by a factor of 6 – Brady Gale Jan 30 '20 at 00:13
  • Does this answer your question? [How do I resize an image using PIL and maintain its aspect ratio?](https://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio) – stovfl Jan 30 '20 at 00:34

0 Answers0