Python 3.x 如何将ImageTk转换为图像?

Python 3.x 如何将ImageTk转换为图像?,python-3.x,tkinter,python-imaging-library,Python 3.x,Tkinter,Python Imaging Library,假设我在变量imgtk中存储了一些ImageTk.PhotoImageimage。如何将其转换回图像。图像 原因是我想调整它的大小,但似乎.resize()仅适用于Image.Images.好的,这并不容易,但我认为我有一个解决方案,尽管您需要使用label.Image的一些私有方法。也许有更好的办法,如果是这样的话,我很想看看 import tkinter as tk from tkinter import Label import numpy as np from PIL import Im

假设我在变量
imgtk
中存储了一些
ImageTk.PhotoImage
image。如何将其转换回
图像。图像


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

好的,这并不容易,但我认为我有一个解决方案,尽管您需要使用
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()
实际上,您可以使用方法
zoom
放大图片(
zoom(2)
使大小加倍)和
subsample
缩小原始图片(
subsample(2)
将图片大小减半)

比如说

picture2 = label1.image._PhotoImage__photo.subsample(4)
将图片的大小减小到四分之一,您可以跳过对图像的所有转换

根据
label1.image.\u PhotoImage.\u photo.subsample.\u doc.\u

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

label1.image.\u PhotoImage.\u photo.zoom.\u doc.\u

返回与此小部件具有相同图像的新照片图像,但在x方向上使用x因子,在y方向上使用y因子进行缩放。如果未给出y,则默认值与x相同


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

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

img = ImageTk.getimage( imgtk )
我刚刚在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()

我想我有办法了,耐心点!有点遗憾的是,似乎没有任何内置的方法可以做到这一点。是的,你会认为应该有一种更直接的方法从小部件中提取图像!:)实际上,
\u PhotoImage\u photo
有两种有趣的方法来增大或减小图片的大小。我已经在答案中添加了这个。非常感谢所有的帮助!我还遇到了这两种方法——包括它们的问题:这两种方法似乎都只能处理整数因子,这意味着你可以将它们都用于分数因子,但根据因子的不同,这可能会消耗大量内存。但可能比通过图像路径更快,这似乎需要花费相当多的时间来填充数组,我不认为我会找到这种方法-我将不得不尝试这种方法,因为它可以节省我相当多的工作:)不客气!show()和close()方法记录在Image模块中,但是ImageTk.getimage()接口函数确实很难找到。实际上,我只是通过查看源代码才找到它的。