Python SVG转换器创建空文件 [英] Python SVG converter creates empty file

查看:97
本文介绍了Python SVG转换器创建空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面有一些代码可以将SVG图像转换为PNG。它可以正常运行,但会创建一个空白的 PNG文件,而不是与原始SVG具有相同图像的PNG文件。我确实发现这不是cairo的错误,而是更多与rsvg有关的错误,我在此处

  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。



我无法终生弄清楚为什么它无法显示正确的图片。

解决方案

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



从wand.api导入库
导入wand.color
导入wand.image

和wand.api导入wand.image.Image( )作为图像:
和wand.color.Color('transparent')作为background_color:
library.MagickSetBackgroundColor(image.wand,
background_color.resource)
image.read( blob = NAMEOFTHEFILE.read(),format = svg)
png_image = image.make_blob( png32)

,其中open(NAMEOFTHENEWFILE, wb)显示为:
out.write(png_image)


I have some code below that is supposed to convert a SVG image to a PNG. It runs without errors but creates a PNG file that is blank instead of one with the same image as the original SVG. I did find that it is not an error with cairo but more one relating to rsvg, which I got 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")

I am using Python 3.6 on Windows 10.

I can't for the life of me figure out why it isn't displaying the correct picture. Any help would be hugely appreciated.

解决方案

If your goal is to convert from SVG to PNG, I would recommend using Wand, as in the following script:

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)

这篇关于Python SVG转换器创建空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆