英文:
Why can't PIL identify SVG images from stream?
问题
I'm working on a system that receives bytes
object containing an image in a format which is not known in advance and is supposed to work with it. I am using PIL
to do the work for me. The documentation says that PIL.Image.open()
can identify the file, even when a file object is passed. I have tried and it works with other file formats. But SVG
files seem to be problematic.
Is there a way to make PIL
work by itself or do I have to identify the image by some other means and then force PIL.Image.open()
to read the image as SVG
?
MRE:
#!/usr/bin/env python3
import requests
import io
import PIL.Image
with requests.get("https://github.githubassets.com/favicons/favicon.svg") as r:
data = r.content
with io.BytesIO(data) as image:
PIL.Image.open(image)
Traceback (most recent call last):
File "MRE.py", line 11, in <module>
PIL.Image.open(image)
File "/usr/lib/python3.11/site-packages/PIL/Image.py", line 3283, in open
raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7fe38b2457b0>
英文:
I'm working on a system that recieves bytes
object containing an image in format which is not known in advance and is supposed to work with it. I am using PIL
to do the work for me. The documentation says that PIL.Image.open()
can identify the file, even when a file object is passed. I have tried and it works with other file formats. But SVG
files seem to be problematic.
Is there a way to make PIL
work by itself or do I have to identify the image by some other means and then force PIL.Image.open()
to read the image as SVG
?
MRE:
#!/usr/bin/env python3
import requests
import io
import PIL.Image
with requests.get("https://github.githubassets.com/favicons/favicon.svg") as r:
data = r.content
with io.BytesIO(data) as image:
PIL.Image.open(image)
Traceback (most recent call last):
File "MRE.py", line 11, in <module>
PIL.Image.open(image)
File "/usr/lib/python3.11/site-packages/PIL/Image.py", line 3283, in open
raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7fe38b2457b0>
答案1
得分: 2
Pillow/PIL 不支持 SVG 输入。
如果您想使用 PIL 处理 SVG 输入,您需要首先将其渲染为光栅图形。可以使用 CairoSVG 模块来实现此操作。
在Python中直接编辑SVG图形没有很好的支持。不过,可以通过编辑底层的XML结构来实现,可以使用 lxml 模块。
英文:
Pillow/PIL does not support SVG input.
You need to render to a raster graphic first if you want to process SVG input with PIL. This can be done, e.g., using CairoSVG module.
There is no good support for editing SVG graphics directly in Python. It can be done, however, by editing the underlying XML structure using lxml module.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论