Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't PIL identify SVG images from stream?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/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>

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading