Href on image

Hello all,

How do I hyperlink when user clicks on an image?
My code to display my gif is the following:
st.sidebar.markdown(
f’cat gif’,
unsafe_allow_html=True,
)

thanks for your help :slight_smile:

Can you try:

st.markdown('''
    <a href="https://docs.streamlit.io">
        <img src="https://media.tenor.com/images/ac3316998c5a2958f0ee8dfe577d5281/tenor.gif" />
    </a>''',
    unsafe_allow_html=True
)
1 Like

thanks @GokulNC. however this only shows the link but not the image (the image is stored locally).
any idea?

image = Image.open('/Path to img')
st.sidebar.markdown('''
    <a href="https://www.example.com/fr/>
        <img src="data:image/gif;base64,{data_url}" alt="cat gif"/>
    </a>''',
    unsafe_allow_html=True
)

Supporting image with anchor href is a very basic requirement but unfortunately missing, so please file an issue in StreamLit GitHub repo for this feature request.

For now, this should help for local images:

import streamlit as st
import os
import base64

@st.cache(allow_output_mutation=True)
def get_base64_of_bin_file(bin_file):
    with open(bin_file, 'rb') as f:
        data = f.read()
    return base64.b64encode(data).decode()

@st.cache(allow_output_mutation=True)
def get_img_with_href(local_img_path, target_url):
    img_format = os.path.splitext(local_img_path)[-1].replace('.', '')
    bin_str = get_base64_of_bin_file(local_img_path)
    html_code = f'''
        <a href="{target_url}">
            <img src="data:image/{img_format};base64,{bin_str}" />
        </a>'''
    return html_code

gif_html = get_img_with_href('tenor.gif', 'https://docs.streamlit.io')
st.markdown(gif_html, unsafe_allow_html=True)
4 Likes

thanks @GokuINC. It perfectly works=)

2 Likes

There are no words to thank you enough :laughing:

2 Likes