【问题标题】:Streamlit image download buttonStreamlit 图像下载按钮
【发布时间】:2022-08-16 10:01:13
【问题描述】:
st.write(\"Preview\")
#openCV image result cropped_image which is an np array
st.image(cropped_image)
#cropped_image converted to PIL image color      
result = Image.fromarray(cropped_image.astype(\'uint8\'), \'RGB\')
    
img = Image.open(result)            

btn = st.download_button(
      label=\"Download image\",
      data=img,
      file_name=\"imagename.png\",
      mime=\"image/png\")
     

我想使用 st.download_button 下载图像结果。我知道我不能使用cropped_image 结果,因为它是一个np 数组。我将图像数组转换为 PIL 图像,但我不知道如何从此处获取结果图像文件名。你能给我一些想法如何解决这个问题吗?

    标签: python streamlit


    【解决方案1】:

    Streamlit download_button 期望数据类型是某种类型。在这里阅读更多:https://github.com/streamlit/streamlit/blob/ba46ad297e8816f0d6a3aa910ce67556239f3e6d/lib/streamlit/elements/button.py#L353

    您可以使用以下 sn-p 将您的 PIL 图像转换为 bytes

    from io import BytesIO
    buf = BytesIO()
    img.save(buf, format="JPEG")
    byte_im = buf.getvalue()
    

    现在您可以使用st.download_button

    btn = col.download_button(
          label="Download Image",
          data=byte_im,
          file_name="imagename.png",
          mime="image/jpeg",
          )
    

    【讨论】:

      【解决方案2】:

      如果您的目录中有图像文件:

      st.download_button(label='Download Image', data= open('yourimage.png', 'rb').read(), file_name='imagename.png', mime='image/png')

      【讨论】:

        猜你喜欢
        • 2023-01-18
        • 1970-01-01
        • 1970-01-01
        • 2017-10-02
        • 2020-09-20
        • 1970-01-01
        • 2016-01-05
        • 2011-02-07
        • 2011-03-18
        相关资源
        最近更新 更多