【问题标题】:Loading image from SQLite database to tkinter window将图像从 SQLite 数据库加载到 tkinter 窗口
【发布时间】:2020-07-24 04:49:54
【问题描述】:

我已使用 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】:

您需要在图像数据上使用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)
      # load the image
      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)

【讨论】:

    【解决方案2】:

    当您使用 ImageTk.PhotoImage 时,它需要 PIL Image 或模式字符串作为第一个参数。

    如果您想提供原始数据,请尝试使用 data 关键字参数:

    render = ImageTk.PhotoImage(data=photo)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2013-06-16
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多