[英]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.