将图像从SQLite数据库加载到tkinter窗口

问题描述 投票:0回答:1

我已使用DBite for SQLite作为Blob将图像保存在SQLite数据库中。我想从数据库中打开Blob数据,然后在窗口中绘制图像。

为此,我正在做这样的事情:

import sqlite3
from PIL import Image, ImageTk

sql_fetch_blob_query = "SELECT * from credentials where id = ?"
c.execute(sql_fetch_blob_query, (id,))
record = c.fetchall()
for row in record:
      print("Id = ", row[0], "Name = ", row[1])
      photo = row[4]    # image saved in the 5th column of database

      # drawing image to top window
      render = ImageTk.PhotoImage(photo)
      img = Label(image=render)
      img.image = render
      img.place(x=0, y=0)

但是它实际上不起作用,并且在窗口中什么也不显示。请帮助我从SQLite数据库将图像绘制到窗口。

错误是终端:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "master.py", line 67, in login
    self.drawWin()
  File "master.py", line 102, in drawWin
    self.drawImage(top)
  File "master.py", line 161, in drawImage
    render = ImageTk.PhotoImage(self.photo)
  File "/usr/lib/python3/dist-packages/PIL/ImageTk.py", line 114, in __init__
    mode = Image.getmodebase(mode)
  File "/usr/lib/python3/dist-packages/PIL/Image.py", line 326, in getmodebase
    return ImageMode.getmode(mode).basemode
  File "/usr/lib/python3/dist-packages/PIL/ImageMode.py", line 64, in getmode
    return _modes[mode]
KeyError: b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\

此KeyError持续数百行。

谢谢!

python-3.x tkinter
1个回答
0
投票

您需要在图像数据上使用io.BytesIO()Image.open()

import sqlite3
from PIL import Image, ImageTk
import io

sql_fetch_blob_query = "SELECT * from credentials where id = ?"
c.execute(sql_fetch_blob_query, (id,))
record = c.fetchall()
for row in record:
      print("Id = ", row[0], "Name = ", row[1])
      photo = row[4]    # image saved in the 5th column of database

      # convert the image data to file object
      fp = io.BytesIO(photo)
      image = Image.open(fp)

      # drawing image to top window
      render = ImageTk.PhotoImage(image)
      img = Label(image=render)
      img.image = render
      img.place(x=0, y=0)
© www.soinside.com 2019 - 2024. All rights reserved.