在Tkinter中使用PIL调整图片大小

24

我目前使用PIL在Tkinter中显示图像。我想临时调整这些图像的大小,以便更容易地查看。我该如何做到这一点?

代码片段:

self.pw.pic = ImageTk.PhotoImage(Image.open(self.pic_file))
self.pw.pic_label = TK.Label(self.pw , image=self.pw.pic,borderwidth=0)         
self.pw.pic_label.grid(column=0,row=0)
3个回答

46

这是我的做法,而且它非常有效...

image = Image.open(Image_Location)
image = image.resize((250, 250), Image.ANTIALIAS) ## The (250, 250) is (height, width)
self.pw.pic = ImageTk.PhotoImage(image)

好的,给你:

看这里 :)

编辑:

这是我的导入语句:

from Tkinter import *
import tkFont
from PIL import Image

下面是我从这个示例中改编出来的完整可用代码:

im_temp = Image.open(Image_Location)
im_temp = im_temp.resize((250, 250), Image.ANTIALIAS)
im_temp.save("ArtWrk.ppm", "ppm") ## The only reason I included this was to convert
## The image into a format that Tkinter woulden't complain about
self.photo = PhotoImage(file="ArtWrk.ppm") ## Open the image as a tkinter.PhotoImage class()
self.Artwork.destroy() ## Erase the last drawn picture (in the program the picture I used was changing)
self.Artwork = Label(self.frame, image=self.photo) ## Sets the image too the label
self.Artwork.photo = self.photo ## Make the image actually display (If I don't include this it won't display an image)
self.Artwork.pack() ## Repack the image

以下是PhotoImage类文档:http://www.pythonware.com/library/tkinter/introduction/photoimage.htm

注意...在查看pythonware上的ImageTK的PhotoImage类文档之后(非常简洁),如果您的代码片段有效,则只要导入PIL“Image”库和PIL“ImageTk”库,并且PIL和tkinter都是最新的,那么此代码片段也应该有效。另外一件事,我甚至找不到“ImageTk”模块。您能否发布您的导入方式?


6
我一直收到这个“AttributeError: PhotoImage实例没有'resize'属性”的错误。我需要导入什么? - rectangletangle
这是(宽度,高度),而不是(高度,宽度)。 - Jacob
使用 PIL 的 ImageTk 明显是更简单的方法。 - martineau

7

如果您不想保存它,可以尝试一下:

from Tkinter import *
from PIL import Image, ImageTk

root = Tk()

same = True
#n can't be zero, recommend 0.25-4
n=2

path = "../img/Stalin.jpeg" 
image = Image.open(path)
[imageSizeWidth, imageSizeHeight] = image.size

newImageSizeWidth = int(imageSizeWidth*n)
if same:
    newImageSizeHeight = int(imageSizeHeight*n) 
else:
    newImageSizeHeight = int(imageSizeHeight/n) 

image = image.resize((newImageSizeWidth, newImageSizeHeight), Image.ANTIALIAS)
img = ImageTk.PhotoImage(image)

Canvas1 = Canvas(root)

Canvas1.create_image(newImageSizeWidth/2,newImageSizeHeight/2,image = img)      
Canvas1.config(bg="blue",width = newImageSizeWidth, height = newImageSizeHeight)
Canvas1.pack(side=LEFT,expand=True,fill=BOTH)

root.mainloop()

3

最简单的方法可能是基于原始图像创建一个新图像,然后用较大的副本替换原始图像。为此,tk图像具有copy方法,可在制作副本时缩放或子采样原始图像。不幸的是,它只允许您以2的倍数进行缩放/子采样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接