【发布时间】:2020-08-29 13:14:57
【问题描述】:
我在 sqlite3 数据库列配置文件中将图像保存为 BLOB - 我调用了带有相关信息的函数 insertBLOB:
sqliteConnection = sqlite3.connect('image_try.db')
cursor = sqliteConnection.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS images (
id INTEGER PRIMARY KEY,
fullname TEXT,
username TEXT,
profile BLOB)""")
def convertToBinaryData(filename):
with open(filename, 'rb') as file:
blobData = file.read()
return blobData
def insertBLOB(name, username, photo):
sqliteConnection = sqlite3.connect('image_try.db')
sqliteConnection.text_factory = str
cursor = sqliteConnection.cursor()
sqlite_insert_blob_query = """ INSERT INTO images
(fullname, username, profile) VALUES (?, ?, ?)"""
empPhoto = convertToBinaryData(photo)
data_tuple = (name, username, empPhoto)
cursor.execute(sqlite_insert_blob_query, data_tuple)
sqliteConnection.commit()
我尝试像这样访问图像文件(这样我可以在标签中显示它) - 通过调用函数 readBlobData:
def writeTofile(data):
# Convert binary data to proper format and write it on Hard Disk
this = open(data, 'rb')
this.open(io.BytesIO(base64.b64decode(data)))
return this
def readBlobData(empId):
try:
sqliteConnection = sqlite3.connect('image_try.db')
sqliteConnection.text_factory = str
cursor = sqliteConnection.cursor()
sql_fetch_blob_query = """SELECT * from images where id = ?"""
cursor.execute(sql_fetch_blob_query, (empId,))
record = cursor.fetchall()
profile = record[0][3] #Blob object
profile = writeTofile(profile)
image = ImageTk.PhotoImage(profile)
image_label = Label(root, image=image)
image_label.photo = image
image_label.pack()
cursor.close()
当我调用函数 readBlobData 我得到这个错误:
Traceback (most recent call last):
File "C:/Users/hilab/PycharmProjects/dafyProject/addimage.py", line 90, in
<module>
readBlobData(1)
File "C:/Users/hilab/PycharmProjects/dafyProject/addimage.py", line 67, in
readBlobData
profile = writeTofile(profile)
File "C:/Users/hilab/PycharmProjects/dafyProject/addimage.py", line 51, in
writeTofile
this = open(data, 'rb')
TypeError: file() argument 1 must be encoded string without NULL bytes, not str
您知道问题所在吗?我该如何解决?如何从 SQLite 数据库访问 BLOB 对象并呈现它???
【问题讨论】:
-
我是否必须将 Blob 图像从数据库中保存到我的计算机上才能显示? (我正在使用具有多个客户端的服务器)
-
您能否在edit 问题中包含complete 错误回溯和用于创建
images表的CREATE TABLE语句。 -
我更新了问题@snakecharmerb
-
数据库表中的
profile应该是磁盘上图像文件的路径,对吗? -
不,它是图像的“二进制数据”表示。使用字节呈现图像。
标签: python image sqlite blob binary-data