能否使用Streamlit开发移动端应用?求带拍照裁剪功能的示例
基于Streamlit的移动端拍照+图片裁剪应用示例
1. 依赖安装
先安装所需的Python包:
pip install streamlit streamlit-cropper pillow
2. 完整实现代码
import streamlit as st from streamlit_cropper import st_cropper from PIL import Image # 页面配置:适配移动端显示 st.set_page_config( page_title="移动端拍照裁剪工具", layout="centered", initial_sidebar_state="collapsed", # 收起侧边栏,适配手机屏幕 ) st.title("📸 拍照并裁剪图片") # 1. 拍照或上传图片 source_img = st.camera_input("点击拍照") if not source_img: source_img = st.file_uploader("或上传图片", type=["png", "jpg", "jpeg"]) # 2. 图片裁剪处理 if source_img: # 将上传/拍摄的图片转为PIL格式 img = Image.open(source_img) # 设置裁剪参数:支持移动端触摸拖拽调整 st.subheader("调整裁剪区域") cropped_img = st_cropper( img, aspect_ratio=None, # 自由比例,也可设为(1,1)正方形、(16,9)等 box_color="#ff0000", # 裁剪框颜色 return_type="pil", # 返回PIL格式图片 realtime_update=True # 实时预览裁剪效果 ) # 3. 显示裁剪结果 st.subheader("裁剪后的图片") st.image(cropped_img, use_column_width=True) # 4. 保存裁剪后的图片 if st.button("保存图片"): cropped_img.save("裁剪后的图片.jpg") st.success("图片已保存到本地!")
关键功能说明
- 移动端拍照:
st.camera_input是Streamlit原生组件,在移动端会直接调用系统相机,拍摄完成后自动上传。 - 图片裁剪:
streamlit-cropper组件支持触摸拖拽调整裁剪框,实时预览效果,完全适配移动端操作。 - 页面适配:通过
initial_sidebar_state="collapsed"收起侧边栏,layout="centered"让内容居中,优化手机屏幕显示体验。
使用提示
- 本地运行代码后,在手机浏览器输入电脑的本地IP地址+Streamlit运行端口(比如
http://192.168.xxx.xxx:8501),确保手机和电脑在同一局域网。 - 若需要部署到公网,可使用Streamlit Cloud等平台,直接分享链接即可在移动端访问。
内容的提问来源于stack exchange,提问作者Keerthi
相关产品推荐
相关产品推荐

