如何解决使用tkin时Base64图像错误

2024-05-16 01:07:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用tkinter显示base64图像。 我正在jupyter笔记本上运行python3。你知道吗

基于this question,我做了以下工作:

  1. 我导入PNG图像并将其转换为base64格式

  2. 我试着用Tkinter打开它

    import base64
    
    with open("IMAGE.png", "rb") as image_file:
        image_data_base64_encoded_string = base64.b64encode(image_file.read()) 
    
    
    
    import tkinter as tk
    from PIL import ImageTk, Image
    
    root = tk.Tk()
    
    im = ImageTk.PhotoImage(data=image_data_base64_encoded_string)
    
    tk.Label(root, image=im).pack()
    
    root.mainloop()
    

    我得到一个错误:

    OSError                                   Traceback (most recent call last)
    <ipython-input-34-96dab6b5d11a> in <module>()
          5 root = tk.Tk()
          6 
    ----> 7 im = ImageTk.PhotoImage(data=image_data_base64_encoded_string)
          8 
          9 tk.Label(root, image=im).pack()
    
    ~\Anaconda3\lib\site-packages\PIL\ImageTk.py in __init__(self, image, size, **kw)
         92         # Tk compatibility: file or data
         93         if image is None:
    ---> 94             image = _get_image_from_kw(kw)
         95 
         96         if hasattr(image, "mode") and hasattr(image, "size"):
    
    ~\Anaconda3\lib\site-packages\PIL\ImageTk.py in _get_image_from_kw(kw)
         62         source = BytesIO(kw.pop("data"))
         63     if source:
    ---> 64         return Image.open(source)
         65 
         66 
    
    ~\Anaconda3\lib\site-packages\PIL\Image.py in open(fp, mode)
       2655         warnings.warn(message)
       2656     raise IOError("cannot identify image file %r"
    -> 2657                   % (filename if filename else fp))
       2658 
       2659 #
    
    OSError: cannot identify image file <_io.BytesIO object at 0x000001D476ACF8E0>
    

有人知道怎么解决这个问题吗?你知道吗


Tags: inimageimportdataifpilrootopen
1条回答
网友
1楼 · 发布于 2024-05-16 01:07:27

看起来您链接到的问题使用了tkinter.PhotoImage类,它与您的代码所使用的PIL.ImageTk.PhotoImage类具有不同的接口。后者接受一个普通的bytes对象。你不需要先对它进行base64编码。你知道吗

import base64

with open("IMAGE.png", "rb") as image_file:
    image_data = image_file.read()


import tkinter as tk
from PIL import ImageTk, Image

root = tk.Tk()

im = ImageTk.PhotoImage(data=image_data)

tk.Label(root, image=im).pack()

root.mainloop()

或者,保持base64编码数据,但使用tkinter.PhotoImage。你知道吗

import base64

with open("IMAGE.png", "rb") as image_file:
    image_data_base64_encoded_string = base64.b64encode(image_file.read()) 


import tkinter as tk
from PIL import Image

root = tk.Tk()

im = tk.PhotoImage(data=image_data_base64_encoded_string)

tk.Label(root, image=im).pack()

root.mainloop()

相关问题 更多 >