图像在PhotoImage下调整大小

ale*_*dro 17 python tkinter

我需要调整图像大小,但我想避免使用PIL,因为我无法在OS X下使其工作 - 不要问我为什么...

无论如何,因为我对gif/pgm/ppm感到满意,所以PhotoImage类对我来说还可以:

photoImg = PhotoImage(file=imgfn)
images.append(photoImg)
text.image_create(INSERT, image=photoImg)
Run Code Online (Sandbox Code Playgroud)

问题是 - 如何调整图像大小?以下只适用于PIL,即非PIL等效?

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

谢谢!

Mem*_*mes 12

因为这两个 zoom()subsample()希望整数作为参数,我用这两种.

我不得不将320x320图像调整为250x250,我最终得到了

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)
Run Code Online (Sandbox Code Playgroud)

  • `AttributeError:'PhotoImage'对象没有属性'zoom' (5认同)

Con*_*ius 10

您必须使用该类subsample()zoom()方法PhotoImage.对于第一个选项,您首先必须计算比例因子,只需在以下行中解释:

scale_w = new_width/old_width
scale_h = new_height/old_height
photoImg.zoom(scale_w, scale_h)
Run Code Online (Sandbox Code Playgroud)

  • <几乎>我需要什么!唯一的问题是,zoom()需要整数参数,这有点奇怪,因为我可能想将其从640x480缩放到320x240:在这种情况下,我会得到zoom(0,0)。或放大倍数小于2倍 (3认同)

小智 10

如果你没有安装 PIL --> 安装它

(对于 Python3+ 用户 --> 在 cmd 中使用“pip install Pillow”)

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()
Run Code Online (Sandbox Code Playgroud)

  • 这个问题问的是没有PIL怎么做。 (6认同)