Is there a known bug with st.image(…) when displaying GIFs or do I need to modify my code in some way. If I display a GIF from online, using a URL it works but the same image, downloaded locally i not animated.
My understanding is that st.image is more for displaying a static image rather than a gif (I could be wrong). Nevertheless, you could follow this route to display GIFs.
Load the PIL library: from PIL import Image
Load base 64: import base64
Convert your local GIF: mygif = base64.b64encode(open(pxfl, 'rb').read()).decode()
where pxfl = path and filename of your local GIF
Use markdown: st.markdown(f"""<img src="data:png;base64,{mygif}" width='50' height='50' >""", True)
Adjust height & width as required (or pass them as parameters to your picture display function)
It has been known for me for some time and I think it is actually a bug. This happens because you are modifying the image (with the parameter width). For URLs, Streamlit just pass the URL and the width to the browser. For local files, Streamlit modifies the image and then serve the modified image. To understand this better:
Thank you both. Based on both of your feedback, I have a solution.
I am attempting to replicate the behavior of st.image and I believe this is close.
Part of my struggles in replicating the aesthetics was getting the caption to center under the image but not have both show up in the middle of the page.
Thank you again.
import streamlit as st
import base64
def displayLocalGIF1(placeholder, imagePath, caption):
placeholder.image(
imagePath,
use_column_width=False, # Disable container width
width=100, # Set the width
caption=caption # Optional caption
)
def displayLocalGIF2(placeholder, localImagePath, caption):
imgFile = open(localImagePath, "rb")
contents = imgFile.read()
imgData = base64.b64encode(contents).decode("utf-8")
imgFile.close()
# Define CSS styles for the container and caption
container_style = (
"position: relative;" # Enable relative positioning
"display: inline-block;" # Display as inline-block to align with placeholder
)
caption_style = (
"font-size: 14px;" # Adjust the font size as needed
"color: #888888;" # Dimmer color
"text-align: center;" # Center the caption text
)
# Display the GIF and caption with positioning relative to the placeholder
placeholder.markdown(f"""<div style="{container_style}">
<img src="data:image/gif;base64,{imgData}" width='100' height='100'>
<p style="{caption_style}">{caption}</p>
</div>""", unsafe_allow_html=True)
image_placeholder1 = st.empty()
image_placeholder2 = st.empty()
imagePath1 = "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif"
imagePath2 = "/PathToUsersFolder/Rotating_earth_(large).gif"
displayLocalGIF1(image_placeholder1, imagePath1,"Remote Image")
displayLocalGIF2(image_placeholder2, imagePath2,"Local Image")