
streamlit 在数据科学家中很受欢迎,因为您通常不需要前端知识。
它们提供简单且易于实现的元素和小部件,无需编写太多代码。
我在 ml/ai 项目中多次使用了 streamlit,体验非常棒。你可以更专注于编写逻辑,前端部分(设计、布局等)由streamlit处理得很好。
我使用 streamlit 和 python 创建了一个演示 web 应用程序,以便您可以理解我在说什么。
这个网络应用程序是将图像格式转换为另一种格式,例如,如果您的图像是 png 格式,您可以将其转换为 jpeg 图像。
以下代码制作了 web 应用程序的用户界面。
import streamlit as st
from imgconvrtr import convert_img_format
from pil import image
# webpage setup
st.set_page_config(page_title="image convrtr")
st.title("image converter")
st.write("convert your images in one _click_")
# file uploader
uploaded_file = st.file_uploader(
"upload an image",
type=["png", "jpg", "jpeg", "jfif", "bmp"]
)
if uploaded_file is not none:
# show the uploaded image
img = image.open(uploaded_file)
st.image(img, caption="uploaded image", use_column_width=true)
# show original image format
st.write(f"original format: {img.format}")
# output format selection
format_options = ["png", "jpeg", "jfif", "bmp"]
output_format = st.selectbox("choose output format", format_options)
# convert the image
if img.format != output_format:
if st.button("convert"):
converted_img = convert_img_format(uploaded_file, output_format.lower())
st.write(f"image converted to {output_format}")
# download button
st.download_button(
label=f"download as {output_format}",
data=converted_img,
file_name=f"image.{output_format.lower()}",
mime=f"image/{output_format.lower()}"
)
else:
st.write("select a different format... yo!")
现在您已经大致了解了这个网络应用程序的用途。我们可以直接跳到讨论此代码中使用的组件。
一开始,你可以看到 st.title 和 st.write 等页面元素,分别用于设置页面标题和在页面上显示文本。
接下来,您可以看到一个用于上传文件的小部件(在本例中用于上传图像)。看看创建文件上传器是多么容易。
st.image 用于显示用户上传的图片。
然后我们有一个下拉菜单来选择使用选择框(st.selectbox)小部件创建的各种格式。
现在,您可以看到我们有两个按钮(st.button 和 st.download_button)。它们都是一样的,但都是为了方便。
st.button 显示我们在这里用于图像转换的按钮小部件。
当用户需要直接从应用程序下载文件时,st.download_button 非常有用。
streamlit 提供了许多用于不同目的的元素和小部件。
现在如果你想尝试这个网络应用程序,你需要安装所需的库:
pip install streamlit pillow
这是图像转换函数:
from pil import image
import io
# function to convert image format
def convert_img_format(image_file, frmat):
with image.open(image_file) as img:
output_img = io.bytesio()
img.save(output_img, format=frmat.upper())
output_img.seek(0)
return output_img
使用以下命令运行应用程序:
streamlit run <script_name>.py
将 <scipt_name> 替换为实际脚本名称。
现在就这些。
继续编码✌✌
以上就是使用 Streamlit 制作 Web 应用程序是如此简单的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号