Home > database >  Converting SVG to PNG python
Converting SVG to PNG python

Time:07-31

I'm having problems converting an SVG to a PNG in python. I'm using Cairosvg and this is what my code looks like.

from cairosvg import svg2png

f = open(f"{filename}.svg")
svg2png(bytestring=f.read().encode("utf-8"),write_to=f"{filename}.png")
f.close()

However it always comes up with this error.

Traceback (most recent call last):
  File "d:\PycharmProjects\QR Code Scanner\main.py", line 1, in <module>
    import QrUtil
  File "d:\PycharmProjects\QR Code Scanner\QrUtil.py", line 11, in <module>
    from cairosvg import svg2png
  File "D:\PycharmProjects\QR Code Scanner\venv\lib\site-packages\cairosvg\__init__.py", line 26, in <module>
    from . import surface  # noqa isort:skip
  File "D:\PycharmProjects\QR Code Scanner\venv\lib\site-packages\cairosvg\surface.py", line 9, in <module>
    import cairocffi as cairo
  File "D:\PycharmProjects\QR Code Scanner\venv\lib\site-packages\cairocffi\__init__.py", line 48, in <module>
    cairo = dlopen(
  File "D:\PycharmProjects\QR Code Scanner\venv\lib\site-packages\cairocffi\__init__.py", line 45, in dlopen
    raise OSError(error_message)  # pragma: no cover
OSError: no library called "cairo-2" was found
no library called "cairo" was found
no library called "libcairo-2" was found
cannot load library 'libcairo.so.2': error 0x7e
cannot load library 'libcairo.2.dylib': error 0x7e
cannot load library 'libcairo-2.dll': error 0x7e

Can anybody help, even if you can suggest a better way to do it?

CodePudding user response:

Have you tried using pyvips ?

import pyvips

image = pyvips.Image.new_from_file("something.svg", dpi=300)
image.write_to_file("x.png")

If you want to learn more, check out the answer here

CodePudding user response:

I would guess that you probably don't have GTK installed. According to a similar bug report on GitHub, Cairo depends on GTK. Once I installed GTK, I was able to use Cairo to convert an SVG to PNG using your code.

Alternatively, you can try SVGLib:

from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM

drawing = svg2rlg("file.svg")
renderPM.drawToFile(drawing, "file.png", fmt="PNG")
  • Related