0
import mysql.connector
import base64
import io
from base64 import b64decode
from PIL import Image


import PIL.Image
with open(r'assets\zoha.jpeg', 'rb') as f:
photo = f.read()
encodestring = base64.b64encode(photo)
db= 
mysql.connector.connect(user="root",password="",
host="localhost",database="pythonfacedetection")
mycursor=db.cursor()
sql = "INSERT INTO image(img) VALUES(%s)"
mycursor.execute(sql,(encodestring,))
db.commit()
sql1="select img from image"
mycursor.execute(sql1)
data = mycursor.fetchall()
data = '{"u": "test"}'
data1=base64.b64decode(data[0][0])
file_like=io.BytesIO(data1)
img=PIL.Image.open(file_like)
img.show()
db.close()

This code can store the image successfully on database but can not show the image. How can I solve this? This error message shows:

Traceback (most recent call last):
  File "C:/Users/MDSHADMANZOHA/PycharmProjects/ImageFromDatabase/main.py", line 44, in <module>
    img=PIL.Image.open(file_like)
  File "C:\Users\MDSHADMANZOHA\PycharmProjects\ImageFromDatabase\venv\lib\site-packages\PIL\Image.py", line 3009, in open
    "cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x000002AF399CF200>
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • Does this answer your question? [Inserting and retrieving images into mysql through python](https://stackoverflow.com/questions/22141718/inserting-and-retrieving-images-into-mysql-through-python) – mnikley Mar 02 '22 at 13:13
  • I highly recommend reading the answers and associated links to other similar questions at https://stackoverflow.com/questions/815626/to-do-or-not-to-do-store-images-in-a-database. It will broaden your perspective on storing files in databases. – Sam M Mar 03 '22 at 05:42

0 Answers0