Search code examples
pythondjangosvgpython-imaging-library

How get resolution of SVG image in python?


Is there any way to get the resolution of an SVG image in python. All other image resolution works fine with PIL. I don't get any solution for SVG image.I am using following code to get the resolution but it works only for some cases,

data = request.FILES['picture']
tree = ET.parse(data)
root = tree.getroot()
h = int(root.attrib['height'])
w = int(root.attrib['width'])
print(h, w)

Solution

  • SVG files are vectors and can be read as XML. for example, xml.etree.ElementTree in the Python standard library can parse XML files.

    We have something line this :

    <svg width="240" height="240" xmlns="http://www.w3.org/2000/svg">
    

    If your file has width and height attributes, you can use them. Without width and height i don't think there is a way to get exactly size of SVG file because they can scale infinitely ( any resolution )

    Width and height

    <svg width="240" height="240" 
    xmlns="http://www.w3.org/2000/svg">
    

    Doubles the original scale.

    <svg viewBox="0 0 120 120" width="240" height="240" 
    xmlns="http://www.w3.org/2000/svg">
    

    Infinite scaling

    <svg viewBox="0 0 120 120" 
    xmlns="http://www.w3.org/2000/svg">