user2966197
user2966197

Reputation: 2981

streamlit app not loading background image

I am building a steamlit page with multipage support and want to put a background image and another banner image in it. When I run the app, I see the banner image but the background image is not showing. Here is my code:

import os
import streamlit as st
import numpy as np
from PIL import  Image

# Custom imports
from multipage import MultiPage
from pages import page1 # import your pages here

import base64


@st.cache_data
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
#
#This image doesn't show
set_png_as_page_bg('./image/log.jpg')

# Create an instance of the app
app = MultiPage()

# This image loads
display = Image.open('./image/log2.jpeg')

st.image(display, width = 400)

col1, col2 = st.columns(2)

col2.title("Content Summarizer and Q&A")

# Add page
app.add_page("Welcome", page1.app)

# The main app
app.run()

The image I want to load for background is in the same code directory as other image but it doesn't show up on page and neither it throws any error. I have tried to move the background image code to page.py as well and same behavior there as well.

Upvotes: 0

Views: 589

Answers (1)

Jamiu S.
Jamiu S.

Reputation: 5721

In your <style> tag, use .stApp class instead of body to set the background:

...
page_bg_img = '''
     <style>
     .stApp {
     background-image: url("data:image/png;base64,%s");
     background-size: cover;
     }
     </style>
     ''' % bin_str

Upvotes: 1

Related Questions