How do I use a background image on streamlit

Hello, I would like to put a background image in my API with streamlit. It seems like my css file is not enough.
Thank you

1 Like

The following should help you set a page’s background image using a picture’s URL:

page_bg_img = '''
<style>
body {
background-image: url("https://images.unsplash.com/photo-1542281286-9e0a16bb7366");
background-size: cover;
}
</style>
'''

st.markdown(page_bg_img, unsafe_allow_html=True)
6 Likes

Thank you it works but when I use a local image it doesn’t and I don’t know why

The reason why you can’t serve a local image is because the CSS code is relative to the browser, which doesn’t have access to your local computer for security reasons (this is a webserver thing, not a Streamlit decision per se).

Implementing this GitHub issue would fix this issue:

To solve the issue now, it might be possible to pass a bytes object somehow in your CSS, but I’m not familiar with exactly how you might do that.

Thank you for your response, I can’t seem to find the answer.
I get this :
KeyError: ‘public_folder’

Traceback:

File "c:\users\rajhi\anaconda3\lib\site-packages\streamlit\ScriptRunner.py", line 319, in _run_script
    exec(code, module.__dict__)File "C:\Users\rajhi\Liquidity\Code\dev\app.py", line 7, in <module>
    st.set_option('public_folder', 'static')File "c:\users\rajhi\anaconda3\lib\site-packages\streamlit\__init__.py", line 210, in set_option
    opt = _config._config_options[key]

Here you go, wrote this for you.
Use this to set local image as page’s background:

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()

def set_png_as_page_bg(png_file):
    bin_str = get_base64_of_bin_file(png_file)
    page_bg_img = '''
    <style>
    body {
    background-image: url("data:image/png;base64,%s");
    background-size: cover;
    }
    </style>
    ''' % bin_str
    
    st.markdown(page_bg_img, unsafe_allow_html=True)
    return

set_png_as_page_bg('background.png')
17 Likes

Wow tremendous code !! Thank you very much you saved my day !

1 Like

Yes, this works. Thank you @GokulNC

1 Like

Hey! Thank you so much for the code. It works for one of my apps, but for the other not.
I used the same exact code as you, do you know what the issue may be?

Works - https://share.streamlit.io/soft-nougat/dqw-ivves/app.py
Doesn’t work - https://share.streamlit.io/soft-nougat/streamlitwebcam/main/web_app.py

@soft-nougat I was facing similar issue. After breaking my head for long time got a solution.

This could be because of different version of streamlit used. Below link solved my issue.

3 Likes

Thanks so much Bhat07! :slight_smile: Good to know this influences the background behaviour.

Not showing background images

what code to write to insert this background image (https://images.app.goo.gl/LFCobouKtT7oZ7Qv7)

Like this worked for me:

st.markdown(
    """
    <style>
    .reportview-container {
        background: url("https://images.app.goo.gl/LFCobouKtT7oZ7Qv7")
    }
   .sidebar .sidebar-content {
        background: url("https://images.app.goo.gl/LFCobouKtT7oZ7Qv7")
    }
    </style>
    """,
    unsafe_allow_html=True
)
1 Like

Tried all the code for adding background images but it didn’t worked.
can you help me out to fix this

1 Like

Hey Ujjwal_Kumar!

I have a couple of hacks that work for me, can you try this one out if you are using one of the later Streamlit versions:

def set_bg_hack(main_bg):
    '''
    A function to unpack an image from root folder and set as bg.
 
    Returns
    -------
    The background.
    '''
    # set bg name
    main_bg_ext = "png"
        
    st.markdown(
         f"""
         <style>
         .stApp {{
             background: url(data:image/{main_bg_ext};base64,{base64.b64encode(open(main_bg, "rb").read()).decode()});
             background-size: cover
         }}
         </style>
         """,
         unsafe_allow_html=True
     )

Just call set_bg_hack(image).

If you are using an older version, this will work:

# set background, use base64 to read local file
def get_base64_of_bin_file(bin_file):
    """
    function to read png file 
    ----------
    bin_file: png -> the background image in local folder
    """
    with open(bin_file, 'rb') as f:
        data = f.read()
    return base64.b64encode(data).decode()

def set_png_as_page_bg(png_file):
    """
    function to display png as bg
    ----------
    png_file: png -> the background image in local folder
    """
    bin_str = get_base64_of_bin_file(png_file)
    page_bg_img = '''
    <style>
    st.App {
    background-image: url("data:image/png;base64,%s");
    background-size: cover;
    }
    </style>
    ''' % bin_str
    
    st.markdown(page_bg_img, unsafe_allow_html=True)
    return

Just call set_png_as_page_bg(image).

8 Likes

suppose i want to set the background image as this url “https://cdn.pixabay.com/photo/2020/06/19/22/33/wormhole-5319067_960_720.jpg” can you pls write the exact code.
I am using the latest version of streamlit.

Hey Ujjwal_Kumar,

Sure thing, I just tested this in my app with the latest Streamlit version and it works:

def set_bg_hack_url():
    '''
    A function to unpack an image from url and set as bg.
    Returns
    -------
    The background.
    '''
        
    st.markdown(
         f"""
         <style>
         .stApp {{
             background: url("https://cdn.pixabay.com/photo/2020/06/19/22/33/wormhole-5319067_960_720.jpg");
             background-size: cover
         }}
         </style>
         """,
         unsafe_allow_html=True
     )

Just call set_bg_hack_url() in your app script. :smiling_face:

6 Likes

Thankyou so much @soft-nougat .
It’s working. :grin:

2 Likes

Hi @soft-nougat! I appreciate you sharing that code snippet. I’m wondering if you would know how to update this to set a local image as the background of the sidebar only?
Thanks!
Tim

1 Like