如何显示存储在我的 SQLite 数据库中的 BLOB 图像?

How to display a BLOB image stored in my SQLite database?

我有一个带有条目和 4 个按钮的 CRUD 表单,用于从我的数据库中删除、更新、创建、获取 值,我想实现另一个按钮来打开图像绑定到我的 id entry 也可以与我的 删除、更新、创建、获取 按钮一起使用,我一直在尝试使用 BLOB 并且我我能够将我的数据库中的图像保存为 BLOB。实际上我知道我需要为 'idvar = StringVar() , namevar = Stringvar()..., etc' 之类的条目创建 textvariables,所以我不确定如何为图像标签创建它以便与我的 CRUD 一起工作按钮 删除、更新、创建、获取

这是我到目前为止得到的代码,它可以很好地将图像保存到我的照片列中:

from tkinter import *
import sqlite3

top = Tk()
top.configure(width='444', heigh='400')

conn = sqlite3.connect('test.db')
c = conn.cursor()

def enterdata():
    id = 'hello'
    photo = convert_pic()
    c.execute('INSERT INTO test (id, photo) VALUES (?, ?)', (id, photo)) #Here my id has integer value and my photo has BLOB value in my database 
    conn.commit()

def convert_pic():
    filename = 'images/image6.jpg'
    with open(filename, 'rb') as file:
        photo = file.read()
    return photo


btn = Button(top, text='save photo', command=enterdata)
btn.place(x='100', y='111')


mainloop()

现在您已经有了 BLOB,您可以使用 io.BytesIO。我将创建一个示例来演示,例如:

from PIL import Image, ImageTk
from io import BytesIO

def show(data):
    img_byte = BytesIO(data)
    img = ImageTk.PhotoImage(Image.open(img_byte))
    Label(root,image=img).pack()
    root.image = img # Keep a reference

现在您可以查询数据库并获取值:

def fetch():
    c = con.cursor()
    id = 1 # Any id
    c.execute('SELECT photo FROM test where id=?',(id,))
    data = c.fetchall()[0][0] # Get the blob data
    show(data) # Call the function with the passes data

这将在根 window 的标签中显示输入的 ID 的图像。