有没有办法直接从 canvas(不显示)显示的字节创建光栅图像?

Is there a way to directly create a raster image from bytes for canvas (not show) display?

我正在 "RGBX" 格式的字节字符串中创建一个 512x512 光栅图像(来自内存映射设备),但无法将其显示在标签图像中。使用 show() 可以很好地显示图像。我只需要将字节数据直接快速传输到按钮或标签的图像输入,这可能吗?

我尝试过使用 .convert 转换图像,但不执行 RGB,PhotoImage 只需要一个字符串变量,base64.b64encode() 在我的机器上生成了一个无法杀死的僵尸。我曾尝试在演示中制作图像对象 'static',我认为大多数类似问题的答案都指向让图像保持显示。我通过打开任何文件加载的图像使用标签或按钮图像方法显示良好。 io.BytesIO 不支持图片插入。

import tkinter as tk
from PIL import Image
#import base64

root=tk.Tk()

kimage_width = 512
kimage_height = 512
kimgSize = (kimage_width,kimage_height)

# Make a color 256K pixel photo of 'stuff', in bytes
# The image data is in RGBX order

ColorImage=b''

for i in range (0,int(kimage_width * kimage_height/8)):
    ColorImage+=bytes([(i>>2) & 0xFF]) # Red
    ColorImage+=bytes([(i>>7) & 0xFF]) # Green
    ColorImage+=bytes([(i>>6) & 0xFF]) # Blue
    ColorImage+=bytes([(i>>0) & 0xFF]) # Not used

# copy it 8 times

ColorImage+=ColorImage+ColorImage+ColorImage # 4
ColorImage+=ColorImage # total = 8 copies

# make a PIL image?

kimage = Image.frombytes('RGBX', kimgSize, ColorImage, 'raw')

kimage.show() # Display image if not a tkinter window

#######photo = base64.b64encode(ColorImage) # Crash - makes a zombie

b=tk.Button(root,justify = tk.LEFT)
b.config(image=kimage, width="512", height="512")
b.pack(side=tk.LEFT)
root.mainloop()

ImageMajick 在 1 window 中显示了 512x512 彩色图像,tk window 应该将相同的图像放入按钮图像中,但是 tk 出错了: _tkinter.TclError: 图片“”不存在

我认为您正在尝试这样做,但遗漏了一些信息:

#!/usr/bin/env python3

import tkinter as tk
from PIL import Image, ImageTk

root=tk.Tk()

kimage_width = 512
kimage_height = 512
kimgSize = (kimage_width,kimage_height)

# Make a color 256K pixel photo of 'stuff', in bytes
# The image data is in RGBX order

ColorImage=b''

for i in range (0,int(kimage_width * kimage_height/8)):
    ColorImage+=bytes([(i>>2) & 0xFF]) # Red
    ColorImage+=bytes([(i>>7) & 0xFF]) # Green
    ColorImage+=bytes([(i>>6) & 0xFF]) # Blue
    ColorImage+=bytes([(i>>0) & 0xFF]) # Not used

# copy it 8 times

ColorImage+=ColorImage+ColorImage+ColorImage # 4
ColorImage+=ColorImage # total = 8 copies

# make a PIL image?

kimage = Image.frombytes('RGBX', kimgSize, ColorImage, 'raw').convert('RGB')

kimage.show() # Display image if not a tkinter window

pI = ImageTk.PhotoImage(kimage)
b=tk.Button(root,justify = tk.LEFT)
b.config(image=pI, width=512, height=512)
b.pack(side=tk.LEFT)
root.mainloop()