如何将 ImageTk 转换为 Image?

fla*_*awr 6 tkinter python-imaging-library python-3.x

假设我ImageTk.PhotoImage在变量中存储了一些图像imgtk。我怎样才能将其转换回Image.Image

原因是我想调整它的大小,但似乎.resize()只适用于Image.Images。

Har*_* K. 6

我知道已经很晚了,但我刚刚遇到了同样的问题,我刚刚发现ImageTk 接口中有一个getimage(imagetk)函数。

因此,要将您的 imgtk 作为 PIL 图像恢复,您可以执行以下操作:

img = ImageTk.getimage( imgtk )
Run Code Online (Sandbox Code Playgroud)

我刚刚在 Windows (Python 3.8.5/Pillow 8.1.2/Tkinter 8.6) 上做了一个快速测试,它似乎工作正常:

# imgtk is an ImageTk.PhotoImage object
img = ImageTk.getimage( imgtk )
img.show()
img.close()
Run Code Online (Sandbox Code Playgroud)


Bru*_*len 3

好吧,这并不容易,但我想我有一个解决方案,尽管您需要进入label.image. 也许有更好的方法,如果是的话我很乐意看到。

import tkinter as tk
from tkinter import Label
import numpy as np
from PIL import Image, ImageTk

root = tk.Tk()

# create label1 with an image
image = Image.open('pic1.jpg')
image = image.resize((500, 750), Image.ANTIALIAS)
picture = ImageTk.PhotoImage(image=image)
label1 = Label(root, image=picture)
label1.image = picture

# extract rgb from image of label1
width, height = label1.image._PhotoImage__size
rgb = np.empty((height, width, 3))
for j in range(height):
    for i in range(width):
        rgb[j, i, :] = label1.image._PhotoImage__photo.get(x=i, y=j)

# create new image from rgb, resize and use for label2
new_image = Image.fromarray(rgb.astype('uint8'))
new_image = new_image.resize((250, 300), Image.ANTIALIAS)
picture2 = ImageTk.PhotoImage(image=new_image)
label2 = Label(root, image=picture2)
label2.image = picture2

# grid the two labels
label1.grid(row=0, column=0)
label2.grid(row=0, column=1)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

其实你可以通过放大图片zoomzoom(2)放大一倍)和subsample缩小(subsample(2)图片减半)的方法来对原始图片进行缩放和缩小。

例如

picture2 = label1.image._PhotoImage__photo.subsample(4)
Run Code Online (Sandbox Code Playgroud)

将图片大小缩小到四分之一,并且您可以跳过所有到图像的转换。

根据label1.image._PhotoImage__photo.subsample.__doc__

基于与此小部件相同的图像返回一个新的 PhotoImage,但仅使用每个 X 或 Y 个像素。如果未给出 y,则默认值与 x 相同

label1.image._PhotoImage__photo.zoom.__doc__

返回一个与此小部件具有相同图像的新 PhotoImage,但在 X 方向上以 x 倍缩放,在 Y 方向上以 y 倍缩放。如果未给出 y,则默认值与 x 相同。