图像在PhotoImage下调整大小

时间:2011-07-05 12:06:32

标签: python tkinter

我需要调整图像大小,但我想避免使用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 个答案:

答案 0 :(得分:11)

因为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)

答案 1 :(得分:8)

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

scale_w = new_width/old_width
scale_h = new_height/old_height
photoImg.zoom(scale_w, scale_h)

答案 2 :(得分:2)

如果您没有安装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()

答案 3 :(得分:1)

我遇到了同样的问题,我发现@ Memes'答案效果很好。请确保尽可能减少您的比例,因为subsample()由于某种原因需要相当长的时间才能运行。

基本上,图像缩小到两种尺寸的最小公因数,然后由原始尺寸补贴。这将为您留下所需大小的图像。

答案 4 :(得分:0)

我有一个要求,我想打开一个图像,调整它的大小,保持纵横比,以新名称保存,并在 tkinter 窗口中显示它(使用 Linux Mint)。在浏览了数十个论坛问题并处理了一些奇怪的错误(似乎涉及 Python 3.x 中的 PIL 到 Pillow fork)之后,我能够开发一些有效的代码,使用预定义的新最大宽度或新最大高度(根据需要放大或缩小)和一个 Canvas 对象,其中图像在框架中居中显示。请注意,我没有包含文件对话框,只是打开并保存一个文件的硬编码图像:

from tkinter import *
from PIL import ImageTk, Image
import shutil,os
from tkinter import filedialog as fd

maxwidth = 600
maxheight = 600

mainwindow = Tk()
picframe = Frame(mainwindow)
picframe.pack()
canvas = Canvas(picframe, width = maxwidth, height = maxheight)  
canvas.pack()

img = Image.open("/home/user1/Pictures/abc.jpg")

width, height = img.size                # Code to scale up or down as necessary to a given max height or width but keeping aspect ratio
if width > height:
    scalingfactor = maxwidth/width
    width = maxwidth
    height = int(height*scalingfactor)
else:
    scalingfactor = maxheight/height
    height = maxheight
    width = int(width*scalingfactor)

img = img.resize((width,height), Image.ANTIALIAS)

img.save("/home/user1/Pictures/Newabc.jpg")

img = ImageTk.PhotoImage(img)     # Has to be after the resize
canvas.create_image(int(maxwidth/2)-int(width/2), int(maxheight/2)-int(height/2), anchor=NW, image=img)   # No autocentering in frame, have to manually calculate with a new x, y coordinate based on a NW anchor (upper left)
相关问题