【问题标题】:Python SVG converter creates empty filePython SVG转换器创建空文件
【发布时间】:2019-10-21 03:26:20
【问题描述】:

我下面有一些代码应该将 SVG 图像转换为 PNG。它运行时不会出错,但会创建一个空白的 PNG 文件,而不是一个与原始 SVG 具有相同图像的文件。我确实发现这不是 cairo 的错误,而是更多与 rsvg 相关的错误,我得到了here

import cairo
import rsvg

img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640,480)
ctx = cairo.Context(img)
handle= rsvghandler.Handle('example.svg')
handle.render_cairo(ctx)
img.write_to_png("svg.png")

我在 Windows 10 上使用 Python 3.6。

我一生都无法弄清楚为什么它没有显示正确的图片。任何帮助将不胜感激。

【问题讨论】:

  • 我试图重现您的问题,但我似乎无法安装 cairo。运行pip install cairo 时,我得到Could not find a version that satisfies the requirement cairo (from versions: )。运行pip install pycairo 时,我收到错误Package cairo was not found in the pkg-config search path.Perhaps you should add the directory containing 'cairo.pc' to the PKG_CONFIG_PATH environment variable。你是怎么得到它的?
  • 我通过在lfd.uci.edu/~gohlke/pythonlibs 使用pip install [wheelname] 下载 Pycairo whl 文件来安装 cairo。我不记得哪个对我有用,但我必须尝试一些才能正确安装。

标签: python python-3.x type-conversion cairo rsvg


【解决方案1】:

如果您的目标是从 SVG 转换为 PNG,我建议您使用 Wand,如以下脚本所示:

from wand.api import library
import wand.color
import wand.image

with wand.image.Image() as image:
    with wand.color.Color('transparent') as background_color:
        library.MagickSetBackgroundColor(image.wand, 
                                         background_color.resource) 
    image.read(blob=NAMEOFTHEFILE.read(), format="svg")
    png_image = image.make_blob("png32")

with open(NAMEOFTHENEWFILE, "wb") as out:
    out.write(png_image)

【讨论】:

  • 感谢您的回答。唯一的问题是我正在使用 cairo,以便我可以将 svg 转换为 png 并在 tkinter 屏幕中显示新图像而不保存它。有没有办法用魔杖做到这一点?
  • @Andoo 我没有在您的问题中看到对此的提及。我建议您发布一个不同的问题。但是,您可以做到这一点的一种方法是使用您保存的文件并在 tkinter 中打开它。 Here you have an example of code to open in tkinter.
  • 我没有意识到删除最后两行会阻止它保存但仍将 PNG 作为变量保存。我想这就是我其他评论的答案。另外,您知道使我的代码工作的任何方法吗? (开罗真的很快)
  • 如何安装 ImageMagick?
  • @Andoo 如果它帮助您解决了问题,请考虑将答案标记为正确。
猜你喜欢
  • 2013-06-06
  • 1970-01-01
  • 2014-01-15
  • 2015-06-30
  • 2017-03-17
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多