Get an image from MySQL database and display via st.image

Summary

I have a database with a bunch of images stored as LONGBLOB (MySQL). I’d like to display those images via st.image() without storing them locally. I’ve Googled stuff here and there and came to the conclusion that BytesIO and TIL must be used, but I couldn’t get along with those libraries, really…

Additional info

I tried to query the image from the database and stupidly pass it (that is <class ‘bytes’> data type) directly to the st.image(), which resulted in the following error:

UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x000002432FCF03B0>

I, then, tried to use TIL and its Image.open() function and that didn’t work out either…

AttributeError: 'bytes' object has no attribute 'read'

Looking for help! :slight_smile:

Access/snippets of your source code would help to understand the issue better or reproduce the errors, but here is a probable solution -

First, you should retrieve the image data from the database using a SQL query, and then convert it to bytes using python built-in bytes() method.

# Convert image data to bytes
image_bytes = bytes(image_data)

Next, create a BytesIO object by passing the image data to its constructor.

from io import BytesIO
# Create a binary stream
image_stream = BytesIO(image_bytes)

Now, use this object as the first argument to the st.image() function.

import streamlit as st
st.image(image_stream, caption='My Image')

Hope this helps.