常见的第三方图片托管服务商有Imgur、Photobucket、Cloudinary等。其实阿里云OSS对象存储很方便但要付费。
这里选用Cloudinary。注册后复制:

代码实现:
import streamlit as st
import cloudinary
import cloudinary.uploader
cloudinary.config(
cloud_name = "djgpnitvi",
api_key = "257597562437113",
api_secret = "xxx" # 直接复制上面
)
# 上传图片到 Cloudinary
def upload_image(image_file):
if image_file is not None:
upload_result = cloudinary.uploader.upload(image_file)
return upload_result["secure_url"]
return None
# 创建文件上传组件
uploaded_file = st.file_uploader("选择头像", type=["jpg", "jpeg", "png"])
# 获取上传图片的 URL
image_url = upload_image(uploaded_file)
# 显示图片
if image_url:
st.image(image_url, width=200)
运行:streamlit run bad/png_st.py --server.address 0.0.0.0 --server.port 4453 --server.enableXsrfProtection=false
这里–server.enableXsrfProtection=false防止跨站请求伪造上传图片时报错AxiosError: Request failed with status code 403错误
运行后如下:

显示成功!
还可以实现自定义聊天的头像:
# 自定义聊天框样式
st.markdown("""
<style>
.chat-message {
display: flex;
align-items: flex-start;
margin-bottom: 20px;
}
.chat-message img {
width: 60px;
height: 60px;
border-radius: 50%;
margin-right: 10px;
}
.chat-message .message-text {
background-color: #f0f0f0;
padding: 10px;
border-radius: 10px;
}
</style>
""", unsafe_allow_html=True)
for msg in st.session_state.messages:
if msg["role"] == "assistant":
if image_url:
st.markdown(f"""
<div class="chat-message">
<img src="{image_url}" alt="User Avatar">
<div class="message-text">{msg["content"]}</div>
</div>
""", unsafe_allow_html=True)
else:
st.markdown(f"""
<div class="chat-message">
<div style="width: 50px; height: 50px; background-color: #e0e0e0; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-right: 10px;">🧑💻</div>
<div class="message-text">{msg["content"]}</div>
</div>
""", unsafe_allow_html=True)
else:
st.chat_message(msg["role"]).write(msg["content"])
效果如下:


3676

被折叠的 条评论
为什么被折叠?



