Streamlit image download button

Viewed 1058
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")
     

I want to use st.download_button to download the image result. I know I cannot use the cropped_image result since it is an np array. I converted the image array to a PIL image but I don't know how I can get the result image filename from here . Could you please give me some ideas how to solve this issue?

2 Answers

The Streamlit download_button expects the data type to be a certain type. Read more here: https://github.com/streamlit/streamlit/blob/ba46ad297e8816f0d6a3aa910ce67556239f3e6d/lib/streamlit/elements/button.py#L353

You can convert your PIL Image to bytes using the following snippet:

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

Now you can use the st.download_button

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

If you have the image file in your directory:

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