Reputation: 31
I wrote a code in python and I got the image from my computer as an object and now I want to get this image from MySQL database. Any idea how can I do it?
Here is my code for getting the image before connecting to the database, I read the image from my folder as an object:
segimg = Image.open("result1.png")
segimg = segimg.convert("RGB")
I want to do the same but now from my database and here is the table of the desired image.
Table: project
project_name: varchar(25) (primary key)
Image: longblob NOT NULL
Any idea how can I do it, and thanks?
Upvotes: 1
Views: 2103
Reputation: 143
I'm not familiar with python but your question bothered me so i did some researches to understand how things work and i did it anyway :p
I hope this is the response you're looking for. Here you are the example i just did.
Connect to database, download the file and finally open it
Imports:
import mysql.connector
from tkinter import *
from PIL import ImageTk, Image
Connect to the database:
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="mydb"
)
Select the image and get the result:
mycursor = mydb.cursor()
mycursor.execute("SELECT image FROM project")
myresult = mycursor.fetchone()
blob = myresult[0]
Create a file from the query result:
with open("filename.png", 'wb') as file:
file.write(blob)
And finally open it with Tkinter:
root = Tk()
img = ImageTk.PhotoImage(Image.open("filename.png"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
Upvotes: 1