Local Image Button

I am trying to insert an image with hyperlink to another website. The image is stored locally in same directory as app.py file.
I tried to do it using pure markdown and html.
Pure Markdown Code:
st.markdown('[![](image.png)](site.com)')
HTML Code:
html = " <a href="site.com"> <img src="image.png"> </a> "' 'st.markdown(html, unsafe_allow_html=True)

In both cases the browser cannot find the image because it is searching for: localhost:8501/image.png instead of my app.py directory.
I tried to add full path โ€˜C://โ€ฆโ€™ too but the problem persists.
Using the st.image function it is not possible to add the hyperlink right?
I had replaced the โ€˜image.pngโ€™ with an online image URL, and that is fine. But really needed to have the image locally.

Any suggestions?

2 Likes

As you rightly pointed out itโ€™s not working because the file you are looking for isnโ€™t being hosted by the server, Not sure if thereโ€™s a better way but I think you have two options here-

  1. Generate base64 of the image and put it in src
    Check this link for reference.
    https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html
  2. If you have a lot of static content consider hosting it on a separate server maybe. then you can use the URL for that static content by the server. ( Just python -m http.server or nginx should do the job )

Hope it helps ! :slight_smile:

3 Likes

Oh, I like the base64 idea. Will take a shot on it. Thank you :wink:

Did it work?
I am encountering the same issue, and have not been able to find a solution yet.

It worked, here is a sample code:

html = f"<a href='{link}'><img src='data:image/png;base64,{image_base64}'></a>"
st.markdown(html, unsafe_allow_html=True)
6 Likes

It works! thank you so much, Iโ€™ve been struggling till I found this. :pray:

Not working for me can you please tell me what is wrong with my code

with open("book.png", "rb") as image_file:
    image_base64 = base64.b64encode(image_file.read())
link="https://miro.com/app/board/o9J_l4IenZg=/"
html = f"<a href='{link}'><img src='data:image/png;base64,{image_base64}'></a>" 
st.markdown(html, unsafe_allow_html=True)

I use the following function for images.

def img_to_bytes(img_path):
    img_bytes = Path(img_path).read_bytes()
    encoded_img = base64.b64encode(img_bytes).decode()
    return encoded_img

Let me know if it works.

1 Like