Skip to content

Instantly share code, notes, and snippets.

@treuille
Last active May 20, 2024 21:42
Show Gist options
  • Save treuille/8b9cbfec270f7cda44c5fc398361b3b1 to your computer and use it in GitHub Desktop.
Save treuille/8b9cbfec270f7cda44c5fc398361b3b1 to your computer and use it in GitHub Desktop.
Workaround: Displaying SVG images in Streamlit
import streamlit as st
import base64
import textwrap
def render_svg(svg):
"""Renders the given svg string."""
b64 = base64.b64encode(svg.encode('utf-8')).decode("utf-8")
html = r'<img src="data:image/svg+xml;base64,%s"/>' % b64
st.write(html, unsafe_allow_html=True)
def render_svg_example():
svg = """
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
"""
st.write('## Rendering an SVG in Streamlit')
st.write('### SVG Input')
st.code(textwrap.dedent(svg), 'svg')
st.write('### SVG Output')
render_svg(svg)
if __name__ == '__main__':
render_svg_example()
@treuille
Copy link
Author

This workaround demonstrates a method to display svg images using Streamlit. Just copy render_svg into your code to use it!

You can also test it now with:

streamlit run https://gist.githubusercontent.com/treuille/8b9cbfec270f7cda44c5fc398361b3b1/raw/19ce438121af7907d5d1527e36d715dcef755bd3/render_svg.py

You will see this:

image

@treuille
Copy link
Author

Note 1: To ensure this works in Chrome, please make sure that your SVG namespace is correct.

Note 2: This has only been tested in Python 3.6.

@Rkubinski
Copy link

Rkubinski commented Dec 10, 2019

Hi,
Im new to streamlit and webdev in general. How would I do this with a local svg file ?
Let's say I have a file in my local directory named "test.svg", how would I import it into this framework.
Thanks!

Edit:
Figure it out:

f = open("test.svg","r")
lines = f.readlines()
line_string=''.join(lines)

render_svg(line_string)

@treuille
Copy link
Author

@Rkubinski : Awesome. Glad you got it to work!!

@dariushazimi
Copy link

@treuille Nice work.

@treuille
Copy link
Author

Thanks, @dariushazimi! 😊

@kentang2017
Copy link

kentang2017 commented Oct 19, 2022

hi, is it possible to display two svg files with the same position in streamlit?

@felipecordero
Copy link

Really helpful, Thanks you so much for sharing!

@arunoruto
Copy link

I guess SVG support has been implemented into the st.image function. Just read the SVG file and put the string as the argument.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment