tags:

views:

293

answers:

2

Currently I'm using rsvg to load the svg (from a string, not from a file) and drawing to cairo. Anyone know a better way? I use PIL elsewhere in my application, but I don't know of a way to do this with PIL.

+1  A: 

Here's what I currently have (is answering my own question the best way to do this?):

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)
colinmarc
@colinmarc Welcome to Stackoverflow! The general rule of thumb is if what you are posting is a way to solve the problem then it may be an answer; if it's context or attempts at solving the problem that do not work, or feel to hacked-together to be a good answer then it should go in the question as an edit. The fact that this code seems to be the 'what you were doing' that you were looking to get comments on, ("Anyone know a better way") rather than a solution to a problem suggests that this should really be in your question.
Sean Vieira
+1  A: 

How about imagemagic? - http://www.imagemagick.org/script/magick-vector-graphics.php It can read/write from/to stdin/stdout so You can integrate it with your app even if You don't want to use files

Maciek Sawicki
ImageMagick `convert` versions older than May 2010 do a horrible job of interpreting SVG. Given the changelog, it doesn't seem like they've yet gotten SVG support working well (although I didn't build it to see).
msw