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

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)
1 Like

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')
4 Likes

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

1 Like