如何将 ImageTk 转换为 Image? [英] How to convert ImageTk to Image?

查看:140
本文介绍了如何将 ImageTk 转换为 Image?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have some ImageTk.PhotoImage image stored in the variable imgtk. How can I convert it back to an Image.Image?

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

The reason is that I want to resize it, but it seems that .resize() only works for Image.Images.

推荐答案

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

Ok, that was not easy but I think I have a solution though you need to go into some private methods of label.image. Maybe there is a better way if so I would love to see.

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) 将图片尺寸减半).

Actually you can zoom and reduce the original picture by using the methods zoom to enlarge the picture (zoom(2) doubles the size) and subsample to reduce the size (subsample(2) halves the picture size).

例如

picture2 = label1.image._PhotoImage__photo.subsample(4)

将图片的大小缩小到四分之一,您可以跳过所有转换为图像的过程.

reduces the size of the picture to a quarter and you can skip all the conversion to an Image.

根据label1.image._PhotoImage__photo.subsample.__doc__:

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

Return a new PhotoImage based on the same image as this widget but use only every Xth or Yth pixel. If y is not given, the default value is the same as x

label1.image._PhotoImage__photo.zoom.__doc__:

返回一个与此小部件具有相同图像的新 PhotoImage,但在 X 方向和 Y 方向使用 x 因子缩放它.如果未给出 y,则默认值与 x 相同.

Return a new PhotoImage with the same image as this widget but zoom it with a factor of x in the X direction and y in the Y direction. If y is not given, the default value is the same as x.

这篇关于如何将 ImageTk 转换为 Image?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆