Python: 如何从 SVG url 获取图像尺寸?

Python: How to get image dimensions from SVG url?

我希望通过 Python 从 URL 获取 SVG 图像。我尝试了以下适用于非 SVG 图像的脚本,但我很难找到适合 SVG 的解决方案:

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)

您不能使用 PIL 读取 SVG(请参阅 their docs 了解兼容的文件格式)。

您可以使用xml.etree.ElementTree加载它。这是因为 SVG 是可以解析为 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}")