如何在Streamlit中保存裁剪后的图片并支持前后查看
Streamlit图片裁剪保存及浏览实现方案
以下是完整的可运行实现,包含裁剪保存、历史图片浏览功能:
import streamlit as st from PIL import Image import os import uuid # 初始化Session State,保存已裁剪图片路径和当前浏览索引 if "cropped_images" not in st.session_state: st.session_state.cropped_images = [] if "current_index" not in st.session_state: st.session_state.current_index = -1 # 创建保存裁剪图片的目录 save_dir = "cropped_images" if not os.path.exists(save_dir): os.makedirs(save_dir) # 上传图片 uploaded_file = st.file_uploader("上传图片", type=["png", "jpg", "jpeg"]) if uploaded_file: # 显示原图 original_img = Image.open(uploaded_file) st.image(original_img, caption="原图", use_column_width=True) # 输入裁剪参数(可替换为滑块等更友好的交互组件) st.subheader("裁剪参数") left = st.number_input("左边界", min_value=0, max_value=original_img.width-1, value=0) top = st.number_input("上边界", min_value=0, max_value=original_img.height-1, value=0) right = st.number_input("右边界", min_value=left+1, max_value=original_img.width, value=original_img.width) bottom = st.number_input("下边界", min_value=top+1, max_value=original_img.height, value=original_img.height) # 裁剪预览 cropped_img = original_img.crop((left, top, right, bottom)) st.image(cropped_img, caption="裁剪预览", use_column_width=True) # 保存裁剪后的图片 if st.button("保存裁剪图片"): # 生成唯一文件名避免覆盖 file_name = f"crop_{uuid.uuid4().hex}.png" save_path = os.path.join(save_dir, file_name) cropped_img.save(save_path) # 添加到历史列表并切换到当前图片 st.session_state.cropped_images.append(save_path) st.session_state.current_index = len(st.session_state.cropped_images) - 1 st.success(f"图片已保存到: {save_path}") # 历史图片浏览区域 if st.session_state.cropped_images: st.subheader("已裁剪图片浏览") # 显示当前图片 current_img_path = st.session_state.cropped_images[st.session_state.current_index] current_img = Image.open(current_img_path) st.image(current_img, caption=f"已裁剪图片 {st.session_state.current_index+1}/{len(st.session_state.cropped_images)}", use_column_width=True) # 浏览按钮 col1, col2 = st.columns(2) with col1: if st.button("上一张"): if st.session_state.current_index > 0: st.session_state.current_index -= 1 with col2: if st.button("下一张"): if st.session_state.current_index < len(st.session_state.cropped_images)-1: st.session_state.current_index += 1 else: st.info("还没有保存任何裁剪后的图片")
关键部分说明
- Session State 维护状态:用
st.session_state存储已裁剪图片的路径列表和当前索引,确保页面刷新时不会丢失历史数据 - 唯一文件名生成:借助
uuid生成随机文件名,避免重复保存时覆盖已有图片 - 裁剪与保存逻辑:使用PIL的
Image.crop()完成裁剪,Image.save()将图片保存到指定目录,同时把路径加入历史列表 - 浏览控制:通过修改
current_index的值,结合边界判断,实现上一张/下一张的切换逻辑,同时显示当前图片的序号信息
内容的提问来源于stack exchange,提问作者SIBA
相关产品推荐
相关产品推荐

