PhotoImage下的图像调整大小
我需要调整一张图片的大小,但我想避免使用PIL,因为我在OS X上无法让它正常工作——别问我为什么。
不过,因为我对GIF/PGM/PPM格式的图片满意,所以使用PhotoImage类对我来说没问题:
photoImg = PhotoImage(file=imgfn)
images.append(photoImg)
text.image_create(INSERT, image=photoImg)
问题是——我该怎么调整图片的大小呢?下面的代码只能在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)
5 个回答
7
如果你还没有安装PIL,那就去安装它
(对于Python3及以上的用户 --> 在命令行中使用 '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()
22
你需要使用PhotoImage
类的subsample()
或zoom()
方法。对于第一个选项,你首先需要计算缩放因子,下面的几行简单解释了这个过程:
scale_w = new_width/old_width
scale_h = new_height/old_height
photoImg.zoom(scale_w, scale_h)
28
因为 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)