Pass path to file_uploader? Goal: click "next" to change uploaded file

Summary

I serving/using streamlit locally. I have a folder of images to process. I have hacked a way to choose images using a text input and a selectbox:

image_path = st.text_input("Path to images", value = "./images")
st.sidebar.markdown("## Images")
all_images = os.listdir(image_path)
selected_image = st.sidebar.selectbox("Choose and image.", options = all_images, format_func=format_labels, on_change=clear_cache)

image

The rest of my code was written based on st.file_uploader() but I would rather choose the image I’m working on from the selectbox. I’m having a hard time loading the image into memory like is done with file_uploader, using st.image() is not working with the rest of my code.

# Does not work with my code
uploaded_file = st.image(os.path.join(image_path, selected_image))
# Works but I want to avoid manually choosing the file, see explanation below
uploaded_file = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"], key="image", on_change = clear_cache) #, accept_multiple_files=True

My real goal is to have a β€œnext” button that changes the image to the next one in the directory. I have +1000 images in the directory so finding the next one through file_uploader is tedious. Does anyone know how to do the equivalent of giving a path to file_uploader?

Thank you very much. You can view the project here GitHub - TristansCloud/StickleMorph at next_button

It is just a matter of reading the bytes in the file.

import io
import os

with open(os.path.join(image_path, selected_image)) as f:
    uploaded_file = io.BytesIO(f.read())
3 Likes

Thank you very much. So glad this is possible!

Little adjustment to your code, needed at least for python v3.7.16 which I am using, is to open the JPEG file in binary mode (, mode="rb")

import io
import os

with open(os.path.join(image_path, selected_image), mode="rb") as f:
    uploaded_file = io.BytesIO(f.read())

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