如何显示存储在我的SQLite数据库中的BLOB图像? [英] How to display a BLOB image stored in my SQLite database?

查看:47
本文介绍了如何显示存储在我的SQLite数据库中的BLOB图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含条目的CRUD表单和4个按钮,用于从我的数据库中删除、更新、创建、获取值,我想实现另一个按钮来打开绑定到我的id条目的图像还可以使用我的删除、更新、创建、获取按钮,我一直在尝试使用BLOB,并且我能够将数据库中的图像另存为BLOB。实际上,我知道我需要为‘idvar=StringVar(),namevar=Stringvar().’等条目创建文本变量,因此我不确定如何为图像标签创建文本变量,以便使用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

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

这篇关于如何显示存储在我的SQLite数据库中的BLOB图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆