Python中服务器端将SVG转换为PNG(或其他图像格式)

14 投票
4 回答
15801 浏览
提问于 2025-04-15 23:18

目前我正在使用rsvg来加载SVG图像(是从字符串加载,而不是从文件),然后用cairo进行绘制。有没有人知道更好的方法?我在应用程序的其他地方使用PIL,但我不知道如何用PIL来做到这一点。

4 个回答

3

我安装了Inkscape,所以我直接用Inkscape的命令来处理,命令是 inkscape -f file.svg -e file.png

我用的代码是:

import subprocess
inkscape_dir=r"C:\Program Files (x86)\Inkscape"
assert os.path.isdir(inkscape_dir)
os.chdir(inkscape_dir)
subprocess.Popen(['inkscape.exe',"-f",fname,"-e",fname_png])

我在用Windows 7,之前遇到了Windows 5错误 [访问被拒绝](大概是这个意思),直到我切换到Inkscape的目录下。

4

那imagemagic怎么样呢? - http://www.imagemagick.org/script/magick-vector-graphics.php 它可以从标准输入读取,也可以写入到标准输出,所以即使你不想使用文件,也可以把它和你的应用程序结合起来。

14

这是我现在的代码:

import cairo
import rsvg

def convert(data, ofile, maxwidth=0, maxheight=0):

    svg = rsvg.Handle(data=data)

    x = width = svg.props.width
    y = height = svg.props.height
    print "actual dims are " + str((width, height))
    print "converting to " + str((maxwidth, maxheight))

    yscale = xscale = 1

    if (maxheight != 0 and width > maxwidth) or (maxheight != 0 and height > maxheight):
        x = maxwidth
        y = float(maxwidth)/float(width) * height
        print "first resize: " + str((x, y))
        if y > maxheight:
            y = maxheight
            x = float(maxheight)/float(height) * width
            print "second resize: " + str((x, y))
        xscale = float(x)/svg.props.width
        yscale = float(y)/svg.props.height

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, x, y)
    context = cairo.Context(surface)
    context.scale(xscale, yscale)
    svg.render_cairo(context)
    surface.write_to_png(ofile)

撰写回答