Manually Adding an Image to Media Folder (Getting Web Path to Files)

This is rather silly and perhaps irresponsible of me since hosting extra files elsewhere is probably simpler, safer, and more reliable. That being said…

I had wanted to add an extra image to my Streamlit App to be made available for use in CSS. Fiddling with the structure, I ended up copying out a snippet from the implementation of st.image to manually slip an extra image in for me.

https://mathcatsand-examples.streamlit.app/background

import streamlit as st
import mimetypes
from streamlit import runtime
from streamlit.runtime import caching

image = './files/cat_background.jpg'
image_id = 'please_do_not_crash'

# Copied from Streamlit's implementation of st.image
def serve_image(image, image_id):
    mimetype, _ = mimetypes.guess_type(image)
    if mimetype is None:
        mimetype = "application/octet-stream"
    url = runtime.get_instance().media_file_mgr.add(image, mimetype, image_id)
    caching.save_media_data(image, mimetype, image_id)
    return(url)

url = serve_image(image, image_id)

Shout out to an alternate solution of passing data to css: How do I use a background image on streamlit - #6 by GokulNC

Just sharing here in case anyone finds it helpful.

Edit: I see when I revisit the app after a time, that the way it’s cached isn’t compatible. I will correct this.
Edit2: I updated the caching method, but will check back to make sure it doesn’t fail over time again.

3 Likes

Hi @mathcatsand - You may find this project of use.

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.

Since this topic recently received a like, adding for posterity: Streamlit now has Static file serving as a native feature so the workaround isn’t needed. :slight_smile: