有没有办法在Python中获取SVG图像的分辨率。所有其他图像分辨率都可以与 PIL 配合使用。我没有得到任何 SVG 图像的解决方案。我使用以下代码来获取分辨率,但它仅适用于某些情况,
data = request.FILES['picture']
tree = ET.parse(data)
root = tree.getroot()
h = int(root.attrib['height'])
w = int(root.attrib['width'])
print(h, w)
SVG 文件是矢量,可以读取为 XML。例如,Python标准库中的xml.etree.ElementTree可以解析XML文件。
我们有这样的东西:
<svg width="240" height="240" xmlns="http://www.w3.org/2000/svg">
如果您的文件有宽度和高度属性,您可以使用它们。如果没有宽度和高度,我认为没有办法获得 SVG 文件的精确大小,因为它们可以无限缩放(任何分辨率)
宽度和高度
<svg width="240" height="240"
xmlns="http://www.w3.org/2000/svg">
将原始规模扩大一倍。
<svg viewBox="0 0 120 120" width="240" height="240"
xmlns="http://www.w3.org/2000/svg">
无限缩放
<svg viewBox="0 0 120 120"
xmlns="http://www.w3.org/2000/svg">
这是该问题的另一种替代解决方案。
import requests
from io import BytesIO
from svgpathtools import svg2paths
# URL of the SVG file
svg_url_example = 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Bananas.svg'
# Fetch the SVG content from the URL
response = requests.get(svg_url_example)
# Check if the request was successful
if response.status_code == 200:
# Read the content of the SVG file
svg_content = BytesIO(response.content)
# Extract paths and attributes
#paths, attributes = svg2paths(svg_content)
attributes = svg2paths(svg_content, return_svg_attributes = True)
print(f"SVG Width: {attributes[2]['width']}")
print(f"SVG Height: {attributes[2]['height']}")
else:
print("Failed to fetch the SVG file.")