Skip to content Skip to sidebar Skip to footer

How To Display A Picture From Mysql Database Using Python?

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 th

Solution 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()

Solution 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()

Post a Comment for "How To Display A Picture From Mysql Database Using Python?"