How streamlit stores media

when i upload a photo and then use st.image() the src of the html img tag is a long string of hexadecimal characters. I’m building a system where i need to know the exact url. is there an easy way to predict it, perhaps a hash or function in the source code ? or is my only option to web scrape my own app ?

Hi @ninth,

Here’s the image_to_url() function that st.image uses to derive the url of an image: streamlit/image.py at 949d97f37bde0948b57a0f4cab7644b61166f98d · streamlit/streamlit · GitHub

I put together an example app that accepts an uploaded image, and uses the image_to_url() function from streamlit.elements.image to return the image url:

import streamlit as st
from streamlit.elements.image import image_to_url, MAXIMUM_CONTENT_WIDTH
from PIL import Image

img = st.file_uploader("upload image", type=["jpg", "png"])
if img:
    test = Image.open(img)
    width, height = test.size  # width is needed for image_to_url()
    if width > MAXIMUM_CONTENT_WIDTH:
        width = MAXIMUM_CONTENT_WIDTH  # width is capped at 2*730 https://github.com/streamlit/streamlit/blob/949d97f37bde0948b57a0f4cab7644b61166f98d/lib/streamlit/elements/image.py#L39
    st.image(img)
    st.write(
        image_to_url(
            image=img,
            width=width,
            clamp=False,
            channels="RGB",
            output_format=img.type,
            image_id=img.id,  # each uploaded file has a file.id
        )
    )

Output:

Do you reckon you could modify this code snippet :point_up: and use it in your system?

Happy Streamlit-ing! :balloon:
Snehan

2 Likes

Hi @ninth :wave:

Here’s an alternative that doesn’t use PIL:

import streamlit as st
from streamlit import config
from streamlit.report import Report
from streamlit.elements.image import (
    _BytesIO_to_bytes,
    _normalize_to_bytes,
    MAXIMUM_CONTENT_WIDTH,
)
from streamlit.media_file_manager import (
    _calculate_file_id,
    _get_extension_for_mimetype,
    STATIC_MEDIA_ENDPOINT,
)

def img_url(image):
    mimetype = image.type
    data = _BytesIO_to_bytes(image)
    data, mimetype = _normalize_to_bytes(data, MAXIMUM_CONTENT_WIDTH, mimetype)
    extension = _get_extension_for_mimetype(mimetype)
    file_id = _calculate_file_id(data=data, mimetype=mimetype)
    URL = Report.get_url(config.get_option("browser.serverAddress"))
    return "{}{}/{}{}".format(URL, STATIC_MEDIA_ENDPOINT, file_id, extension)

img = st.file_uploader("upload image", type=["jpg", "png"])

if img:
    st.image(img)
    st.write(img_url(img))

Output:

Happy Streamlit-ing! :balloon:
Snehan

3 Likes