python中的服务器端SVG到PNG(或其他一些图像格式)

col*_*arc 11 python svg png

目前我正在使用rsvg加载svg(从字符串,而不是从文件)和绘图到cairo.谁知道更好的方法?我在我的应用程序中的其他位置使用PIL,但我不知道如何使用PIL执行此操作.

col*_*arc 12

这是我现在拥有的:

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)
Run Code Online (Sandbox Code Playgroud)

  • 欢迎来到Stackoverflow!一般的经验法则是,如果您发布的是解决问题的方法,那么它可能是一个答案; 如果它是上下文或试图解决不起作用的问题,或者觉得被黑客攻击成为一个好的答案那么它应该作为编辑进入问题.事实上,这段代码似乎是你正在寻找的"你正在做什么",("任何人都知道更好的方式")而不是问题的解决方案,这表明这应该在你的问题中. (3认同)