pythonsvgdimensions

Python: How to get image dimensions from SVG url?


I'm looking to get SVG images from an URL via Python. I have tried below script which works for non-SVG images, but I struggle to find a suitable solution for SVGs:

import requests
from PIL import Image
from io import BytesIO

url = 'http://farm4.static.flickr.com/3488/4051378654_238ca94313.jpg'

img_data = requests.get(url).content    
im = Image.open(BytesIO(img_data))
print (im.size)

Solution

  • You cannot use PIL to read SVGs (refer to their docs for compatible file formats).

    You can use xml.etree.ElementTree to load it. This is as SVGs are vectors that can be parsed as an XML.

    import xml.etree.ElementTree as ET
    from io import BytesIO
    
    import requests
    
    url = "https://placeholder.pics/svg/300"
    
    img_data = requests.get(url).content
    tree = ET.parse(BytesIO(img_data))
    
    width, height = tree.getroot().attrib["width"], tree.getroot().attrib["height"]
    print(f"Width: {width} \nHeight: {height}")