使用Python在Windows上将SVG转换为PNG

10

问题:哪个可重复的过程可以使Windows Python用户将SVG图像渲染为PNG?


许多问题/答案(例如Python中将SVG转换为PNGPython中服务器端SVG到PNG(或其他图像格式),由于下面解释的原因它们不是重复问题)解释了如何使用Python将SVG转换为PNG。

很遗憾,它们都不能直接用于Python+Windows。经过20多分钟的尝试后,我仍然无法做到。更多关于失败尝试的细节:

  • Installing cairo on Windows is not straightforward, we have to use Gohlke's binaries Intalling pycairo with Python 3.7 on Windows :

    pip install pycairo-1.20.0-cp37-cp37m-win_amd64.whl
    
  • Even once cairo is installed, rsvg (from main answers of Server-side SVG to PNG (or some other image format) in python, Convert SVG to PNG in Python) is not available for Windows:

    pip install rsvg   # or pyrsvg
    > ERROR: No matching distribution found for pyrsvg
    
  • Solutions with svglib or reportlab don't work out-of-the-box on Python3 + Windows:

    from svglib.svglib import svg2rlg
    from reportlab.graphics import renderPDF, renderPM
    drawing = svg2rlg("a.svg")
    renderPM.drawToFile(drawing, "file.png", fmt="PNG")
    

    Indeed:

    AttributeError: 'Image' object has no attribute 'fromstring'
    
因此,一个针对Windows的解决方案将非常有帮助。

@IInspectable 我正在寻找一个针对给定图像尺寸(例如width=1000px)的PNG导出功能。(当然,SVG可以无限缩放而不会失去质量,但PNG就不是这样了,但我可以接受这一点)。 - Basj
那个 svglib 的例子在 Windows 上对我有效,我无法重现你的错误。你遇到的问题是特定于某些 SVG 文件吗? - Luke Woodward
@LukeWoodward 你有哪些Python、svglib和reportlab的版本?我会尝试安装相同的版本。 - Basj
只需要最后两个,@LukeWoodward。 - Basj
现在您已经有了解决方案,应该包括对您链接的任一或两个问题的更新答案。 - Peter O.
显示剩余4条评论
1个回答

10

从评论中得知,解决方案是安装svglib版本1.0.1和reportlab 3.5.59。


这个答案真是救命稻草。我原本使用的是reportlab 3.5.49版本,但仍然遇到了Attributerror错误。但是通过必要的更新,现在它可以正常工作了。 - 7bStan
非常感谢,你真的救了我的命。干得好! - user17173390

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接