0

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)
mfcss
  • 1,039
  • 1
  • 9
  • 25
  • You may find this useful:- https://stackoverflow.com/questions/46624831/processing-svg-in-python –  Aug 16 '21 at 14:12

1 Answers1

1

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}")
S P Sharan
  • 1,101
  • 9
  • 18