【发布时间】:2021-08-12 05:34:02
【问题描述】:
我正在尝试将图像作为 BLOB 数据从我的 sql 数据库中插入和检索。
我可以将它作为 BLOB 插入。但是,当我尝试检索它时,检索到的图像被截断。
首先它显示OSError: image file is truncated。通过引用一些帖子,我包含了代码 ImageFile.LOAD_TRUNCATED_IMAGES = True。现在没有错误了。
但图像仍然被截断。
这是我的代码。
from tkinter import *
from PIL import ImageTk,Image
from tkinter import filedialog
import mysql.connector
import io
from PIL import ImageFile
root = Tk()
browse_button = Button(root,text ='Browse',command = lambda:open_file())
browse_button.pack()
display_button = Button(root,text ='display',command =lambda:display_file())
display_button.pack()
def display_file():
ImageFile.LOAD_TRUNCATED_IMAGES = True
person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
cursor_variable = person.cursor()
sql = "SELECT data FROM image_db WHERE id = 5"
cursor_variable.execute(sql)
all_data = cursor_variable.fetchall()
image = all_data[0][0]
image = Image.open(io.BytesIO(image))
image.show()
person.commit()
person.close()
def open_file():
root.filename = filedialog.askopenfilename(initialdir="/Users/write/PycharmProjects/slider/img", title='Select a File',
filetypes=(('png files', '*.png'), ('jpeg files', '*.jpeg'),
('jpg files', '*.jpg')))
my_label = Label(root, text=root.filename).pack()
my_image = ImageTk.PhotoImage(Image.open(root.filename))
path = root.filename
id = '5'
person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
cursor_variable = person.cursor()
thedata = open(root.filename, 'rb').read()
sql = "INSERT INTO image_db (id,data) VALUES ('" + id + "',%s)"
cursor_variable.execute(sql, (thedata,))
person.commit()
person.close()
root.mainloop()
感谢任何帮助。
【问题讨论】:
标签: python mysql tkinter python-imaging-library