You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Streamlit Cloud部署后无法读取PNG图片的技术求助

Streamlit Cloud部署后图片加载失败问题解决

问题说明

本地Anaconda环境运行正常的Streamlit应用,部署到Streamlit Cloud后触发FileNotFoundError,无法读取Images目录下的Headliner.png图片,尝试过ChatGPT和YouTube的方案未解决。

代码片段

from pathlib import Path
import streamlit as st
from PIL import Image
from streamlit_option_menu import option_menu
from Page_Details import home, about, contact

current_directory = Path.cwd()
images_folder = current_directory / 'Images'

try:
    headliner_path = images_folder / 'Headliner.png'
    main_image = Image.open(headliner_path)
    st.image(main_image, caption="Naloxone Awareness", use_column_width=True) 
except FileNotFoundError:
    st.error(f"Image 'Headliner.png' not found in '{images_folder}'. Please check the file path.") 
except Exception as e:
    st.error(f"An error occurred: {e}")

错误信息

FileNotFoundError: This app has encountered an error. The original error message is redacted to prevent data leaks. Full error details have been recorded in the logs (if you're on Streamlit Cloud, click on 'Manage app' in the lower right of your app).

回溯日志

File "/home/adminuser/venv/lib/python3.9/site-packages/streamlit/runtime", line xxx
    exec(code, module.__dict__)
File "/mount/src/naloxone/Volunteer_Website/main.py", line 6, in <module>
    main_image = Image.open('Images/Headliner.png')
File "/home/adminuser/venv/lib/python3.9/site-packages/PIL/Image.py", line xxx
    fp = builtins.open(filename, "rb")

问题原因及解决步骤

  1. 核心问题:工作目录不匹配
    本地环境的Path.cwd()指向你的项目根目录,但Streamlit Cloud的容器中,当前工作目录是系统根目录而非你的代码目录。从回溯能看到,代码实际运行时用了相对路径Images/Headliner.png,但云端代码存放在/mount/src/naloxone/Volunteer_Website/,导致路径错位。

  2. 修正路径获取逻辑
    不要用当前工作目录,改用当前脚本所在目录来构建路径,确保本地和云端路径一致:

    # 获取当前脚本的目录(而非工作目录)
    current_script_dir = Path(__file__).parent
    images_folder = current_script_dir / 'Images'
    
    try:
        headliner_path = images_folder / 'Headliner.png'
        main_image = Image.open(headliner_path)
        st.image(main_image, caption="Naloxone Awareness", use_column_width=True) 
    except FileNotFoundError:
        st.error(f"Image 'Headliner.png' not found in '{images_folder}'. Please check the file path.") 
    except Exception as e:
        st.error(f"An error occurred: {e}")
    
  3. 检查文件结构与大小写

    • 确认代码仓库中存在Images文件夹,且Headliner.png确实在该目录下
    • 云端是Linux环境,文件名大小写敏感,确保本地和云端的文件名完全一致(比如不要本地是headliner.png,云端是Headliner.png)
  4. 添加调试验证
    可以在代码中加入路径输出,部署后查看实际路径是否正确:

    st.write(f"脚本所在目录: {current_script_dir}")
    st.write(f"图片完整路径: {headliner_path}")
    

内容的提问来源于stack exchange,提问作者Ali Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 06:35:33