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()
解决方案
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()