I am trying to insert and retrieve image as BLOB data from my sql database.
I am able to insert it as BLOB. However, when I try to retrieve it,the retrieved image is truncated.
First it showed OSError: image file is truncated
. By referring some posts I included the code ImageFile.LOAD_TRUNCATED_IMAGES = True
. Now there is no error.
But the image is still truncated.
This is my code.
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()
Any help is appreciated.