Is there a way to show .svg url as an image in Streamlit?

Hi,

I am trying to incorporate images for which I have .svg urls into a Streamlit app. Is it possible?

For example, https://restcountries.eu/data/usa.svg

I saw a possible solution here (Workaround: Displaying SVG images in Streamlit · GitHub) which creates an image to show, but I am not sure how to do it for an existing URL.

Please advise.

Thank you in advance!

Hi @Negmat_Mullodzhanov :grinning_face_with_smiling_eyes:

It certainly is possible! Below, we will create an app render_svg.py combining the requests module with the linked workaround to display svg images from an existing URL:

import streamlit as st
import base64
import requests

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)


url = "https://restcountries.eu/data/usa.svg"
r = requests.get(url) # Get the webpage
svg = r.content.decode() # Decoded response content with the svg string

render_svg(svg) # Render the svg string

Save the script and run: streamlit run render_svg.py to see the following in your browser :partying_face::

Feel free to let us know if this is what you had in mind.:balloon:

Happy Streamlit-ing!
Snehan

1 Like

HI Shenan,

Thank you so much!

This solution definitely works.

Is it possible to control the size of the image shown on the app with this solution?

Please advise.

Thank you in advance!
Negmat

Hi @Negmat_Mullodzhanov :slightly_smiling_face:

I’m think it would be much trickier to resize the svg by manipulating the svg string. If you’re not too strict about using only svg images, perhaps consider converting your svg to a png or jpg instead? They are easier to resize. For instance, you could use the pycairo module to convert the svg to a png, resize the output, and show the image using st.image like so:

import streamlit as st
import cairosvg

svg_url = "https://restcountries.eu/data/usa.svg"
my_png = cairosvg.svg2png(url=svg_url, output_width=426, output_height=240)
st.image(my_png)

Here, you would replace the values of output_width and output_height to control the image size.
Does this work?

Best,
Snehan :balloon:

Hi Shenan,

Thanks again for another great suggestion.

I am fine converting from svg to pgn, but after pip installing pycairo and cairosvg, I am still getting errors.

Error Message:
OSError: no library called “cairo” was found no library called “libcairo-2” was found cannot load library ‘libcairo.so.2’: error 0x7e cannot load library ‘libcairo.2.dylib’: error 0x7e cannot load library ‘libcairo-2.dll’: error 0x7e

Are there any other packages I need to install to make it work?

Please advise.

Thanks a lot!
Negmat