728x90

streamlit의 download_button을 활용하여 이미지를 다운로드하는 버튼을 생성하려면

 

1. 먼저 data 인자에 이미지 객체를 전달해주어야하는데

2. 이때 이미지 객체는 btye 객체로 전달해주어야한다.

 

그 과정의 예시는 아래와 같다.

import numpy as np
from PIL import Image
import streamlit as st

from io import BytesIO

# image_array는 rgb가 들어간 list type 변수

# numpy array로 변환
image_array = np.array(image_array)
# 0~1 -> 0 ~ 255 사이의 int type 원소로 변환
converted_image_array = (image_array * 255).astype(np.uint8)
# PIL 객체로 변환
img = Image.fromarray(converted_image_array)
# byte 객체로 변환
buf = BytesIO()
img.save(buf, format="PNG") # JPEG, PNG 등 자유롭게 설정
byte_img = buf.getvalue()
# streamlit download_button 생성
st.download_button(label="Download image", data=byte_img, file_name= 'file_name.png')

 

위와 같이 label을 설정하면 활성화된 다운로드 버튼에 Download image라는 글씨가 쓰여서 나온다.

728x90