import streamlit as st
# 本地 Logo 图片路径
logo_path = "logo.png"
# 使用 st.markdown 结合 HTML 和 CSS 居中显示 Logo 图片
st.markdown(
f"""
<div style="display: flex; justify-content: center; align-items: center; height: 100vh;">
<img src="data:image/png;base64,{logo_path}" style="width: 200px; height: auto;" alt="Logo">
</div>
""",
unsafe_allow_html=True
)
要求用streamlit制作一个网页,网页上部要显示小logo图片,但是st.image居中显示和调整图片大小不能同时进行,所以要借助html和css进行布局设置。但是上述代码并不能显示出logo图片。
原来html src的格式应该是base64的(
数据格式问题: 在 HTML 的 <img>
标签中,src
属性需要指向图片的 URL 或者数据。如果你希望直接在 HTML 中使用本地图片,你需要将图片的内容以 Base64 编码的形式嵌入到 HTML 中。你可以使用 Python 的 base64
模块来实现这一点。
),现更改如下:
import streamlit as st
import base64
# 读取本地 Logo 图片文件
logo_path = "logo.png"
# 将 Logo 图片编码为 Base64 格式
def get_base64_of_bin_file(bin_file):
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
# 获取 Logo 图片的 Base64 编码
logo_base64 = get_base64_of_bin_file(logo_path)
# 使用 st.markdown 结合 HTML 和 CSS 显示 Logo 图片
st.markdown(
f"""
<div style="display: flex; justify-content: center; align-items: center; height: 100vh;">
<img src="data:image/png;base64,{logo_base64}" style="width: 200px; height: auto;" alt="Logo">
</div>
""",
unsafe_allow_html=True
)