Python

【StreamlitでWebアプリ作成】<>GIFファイルを表示する

StreamlitでGIFファイルを表示する場合、st.image()は2021年2月現在では対応しておらず、st.markdown()を応用することで表示できたので紹介します。

components.html()を使うとHTML/CSSにより、Webアプリのデザインをより凝ったものにすることができます。

ライブラリをインポート

import streamlit as st
import base64
import streamlit.components.v1 as stc

マークダウンを使った方法

URLから読み込む

st.markdown("![Alt Text](https://cafe-mickey.com/coffee-life/wp-content/uploads/2021/02/image.gif)")

ローカルファイルから読み込む

file_ = open("image.gif", "rb")
contents = file_.read()
data_url = base64.b64encode(contents).decode("utf-8")
file_.close()

st.markdown(
    f'<img src="data:image/gif;base64,{data_url}" alt="cat gif">',
    unsafe_allow_html=True,
    )

HTML形式を使った方法

components.html()を使う

stc.html('<img width="200" alt="test" src="https://cafe-mickey.com/coffee-life/wp-content/uploads/2021/02/image.gif">')

以上で解説は終わりです。

Mickey@コーヒー好きエンジニア

個人アプリ開発者・絵本作家。iPhone・iPad・Apple Watch向けの無料アプリ50本以上と、親子で楽しめる絵本を一人で企画・制作しています。生き物、学び、暮らしの小さな発見を、アプリ・絵本・映像として届けています。