【发布时间】:2019-04-19 18:42:38
【问题描述】:
我想使用 tkinter 显示 base64 图像。 我在 jupyter notebook 上运行 python 3。
我做了以下,基于this question:
我导入一个 PNG 图像并将其转换为 base64 格式
-
我尝试使用 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>
有人知道怎么解决吗?
【问题讨论】:
-
为什么不通过
image_file.read()?还是直接输入文件名? -
有趣的问题。我注意到即使不涉及 Tkinter,也会发生此错误。
import base64; import io; from PIL import Image;后跟with open("output.png", "rb") as image_file: Image.open(io.BytesIO(base64.b64encode(image_file.read())))会产生同样的错误。 -
@CristiFati 这只是为了演示,以便人们可以轻松地重现我的问题。实际上,我有很多 base64 图像存储在 pandas 数据框中。
标签: python python-imaging-library