问题
I want to display a picture I already saved on the table img, but it gives me an error
cannot identify image file
When it try to open the file_like
.
Cursor and connection use the connection and password to mysql database.
With the following code I wanted to display the picture. What's wrong with it, or is there even a better/easier way?
sql1='select * from img'
connection.commit()
cursor.execute(sql1)
data2=cursor.fetchall()
file_like=cStringIO.StringIO(data2[0][0])
img1=PIL.Image.open(file_like,mode='r').convert('RGB')
img1.show()
cursor.close()
回答1:
When using io.BytesIO
instead of cstringIO
it works fine, also without decoding and encoding. And I also changed type from blob
to mediumblob
, which allows bigger pictures.
import pymysql
import io
from PIL import Image
connection=pymysql.connect(host="localhost",
user="root",
passwd="root",
db="test")
cursor=connection.cursor()
sql1 = 'select * from table'
cursor.execute(sql1)
data2 = cursor.fetchall()
file_like2 = io.BytesIO(data2[0][0])
img1=Image.open(file_like2)
img1.show()
cursor.close()
connection.close()
回答2:
I tested your code and got the same error. So first I saved an image to my db. When I saved it I used base64 encoding and then got the same error when I tried to read. To save I used the code from Inserting and retrieving images into mysql through python, and your code also looks like you got it from the same question/answer.
In this case, the solution is simple. You have to decode the data, that's the part missing in the other answer.
So do a base64.b64decode(data2[0][0])
:
import MySQLdb
import base64
from PIL import Image
import cStringIO
db = MySQLdb.connect(host="localhost",
user="root",
passwd="root",
db="test")
# select statement with explicit select list and where clause instead of select * ...
sql1='select img from images where id=1'
cursor = db.cursor()
cursor.execute(sql1)
data2=cursor.fetchall()
cursor.close()
db.close()
file_like=cStringIO.StringIO(base64.b64decode(data2[0][0]))
img1=Image.open(file_like,mode='r').convert('RGB')
img1.show()
来源:https://stackoverflow.com/questions/45814814/how-to-display-a-picture-from-mysql-database-using-python