使用 Streamlit 制作 Web 应用程序是如此简单

DDD
发布: 2024-10-23 21:25:02
原创
943 人浏览过

Making a Webapp is so EASY with Streamlit

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
登录后复制

替换为实际的脚本名称。


现在就这些。
继续编码✌✌

以上是使用 Streamlit 制作 Web 应用程序是如此简单的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!