[英]How to convert MySQL blob image to base64 string in python?
我在雲服務器中有一個 BLOB 圖像,我想使用Tkinter.Label()
顯示它
在深入研究代碼之前,我必須告訴 mysql 表中存在 blob 文件,並且record
本身確實正確地存儲了表中的一行。 records[0][2]
代表/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwI...
這是代碼片段:
global img
#Connecting Server
mydb= mysql.connector.connect(**config)
cursor = mydb.cursor(buffered=True)
#Fetching Blob Image to Record
sql_fetch_blob_query = """SELECT * from my-Table where id = %s"""
emp_id=4
cursor.execute(sql_fetch_blob_query, (emp_id,))
record = cursor.fetchall()
#Base64 Encoding
base64_encoded= base64.b64encode(record[0][2])
base64_encoded_string= base64_encoded.decode('utf-8')
#Displaying on Tkinter
root=tk.Tk()
img=tk.PhotoImage(data=base64_encoded_string)
myLabel= tk.Label(root,image=img)
myLabel.pack()
root.mainLoop()
這是我得到的錯誤:
_tkinter.TclError: couldn't recognize image data
img=tk.PhotoImage(data=base64_encoded_string)
行上的_tkinter.TclError: couldn't recognize image data
我嘗試將該行更改為img=tk.PhotoImage(data=record[0][2])
並且仍然出現相同的錯誤。
編輯:
我在編碼前打印record[0][2]
,輸出為: b'\\xff\\xd8\\xff\\xe0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00\\x01\\
解決了!
所以事實證明我存儲在雲服務器中的 blob 圖像是PIL.ImageTk.PhotoImage()
可以使用的。 換句話說img=PIL.ImageTk.PhotoImage(data=record[0][2])
是我需要的行! 然后我在我的myLabel= tk.Label(root,image= img)
GUI 上放了一個標簽,即myLabel= tk.Label(root,image= img)
並將root.mainLoop()
更改為root.mainloop()
。
現在我可以將圖像文件上傳到雲服務器並在需要時在我的 GUI 上顯示它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.