0

I have saved the image in an SQLite database using the DB Browser for SQLite as a blob. I want to open the blob data from the database and draw the image in the window.

For that, I am doing something like this:

import sqlite3
from PIL import Image, ImageTk

sql_fetch_blob_query = "SELECT * from credentials where id = ?"
c.execute(sql_fetch_blob_query, (id,))
record = c.fetchall()
for row in record:
      print("Id = ", row[0], "Name = ", row[1])
      photo = row[4]    # image saved in the 5th column of database

      # drawing image to top window
      render = ImageTk.PhotoImage(photo)
      img = Label(image=render)
      img.image = render
      img.place(x=0, y=0)

But it's not working actually and shows nothing in the window. Please help me out in drawing the image to the window from the SQLite database.

Error is the terminal:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "master.py", line 67, in login
    self.drawWin()
  File "master.py", line 102, in drawWin
    self.drawImage(top)
  File "master.py", line 161, in drawImage
    render = ImageTk.PhotoImage(self.photo)
  File "/usr/lib/python3/dist-packages/PIL/ImageTk.py", line 114, in __init__
    mode = Image.getmodebase(mode)
  File "/usr/lib/python3/dist-packages/PIL/Image.py", line 326, in getmodebase
    return ImageMode.getmode(mode).basemode
  File "/usr/lib/python3/dist-packages/PIL/ImageMode.py", line 64, in getmode
    return _modes[mode]
KeyError: b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\

This KeyError continues for hundreds of lines.

Thanks!

2 Answers2

2

You need to use io.BytesIO() and Image.open() on the image data:

import sqlite3
from PIL import Image, ImageTk
import io

sql_fetch_blob_query = "SELECT * from credentials where id = ?"
c.execute(sql_fetch_blob_query, (id,))
record = c.fetchall()
for row in record:
      print("Id = ", row[0], "Name = ", row[1])
      photo = row[4]    # image saved in the 5th column of database

      # convert the image data to file object
      fp = io.BytesIO(photo)
      # load the image
      image = Image.open(fp)

      # drawing image to top window
      render = ImageTk.PhotoImage(image)
      img = Label(image=render)
      img.image = render
      img.place(x=0, y=0)
acw1668
  • 40,144
  • 5
  • 22
  • 34
1

When you use ImageTk.PhotoImage it expects a PIL Image or a mode string as the first argument.

If you want to feed it raw data, try using the data keyword argument:

render = ImageTk.PhotoImage(data=photo)
Roland Smith
  • 42,427
  • 3
  • 64
  • 94