SVG PIL decoder

Patrick Sabin patrick.just4fun at
Thu Oct 1 01:08:28 CEST 2009

Donn wrote:
> Have a look at Cairo (python-cairo) in conjunction with librsvg (python-rsvg) 
> -- that'll fix you up. You can go from an SVG to a PNG/array and thence into 
> PIL if you need to.

Thanks for the tip. Got it work, although it was a bit tricky, as 
resizing doesn't seem to be supported by python-rsvg and 
cairo.ImageSurface.create_from_png doesn't allow StringIO or 
TemporaryFile for some reason (got Memory Error). So the code, if 
someone else needs it or someone can improve it:

def open_svg_as_image(fn, width, height):
     tmpfd, tmppath = tempfile.mkstemp(".png")
     tmpfile = os.fdopen(tmpfd,'w')

     file = StringIO.StringIO()
     svgsurface = cairo.SVGSurface (file, width, height)
     svgctx = cairo.Context(svgsurface)
     svg = rsvg.Handle(file=fn)
     svgwidth = svg.get_property('width')
     svgheight = svg.get_property('height')


     tmpfile = open(tmppath, 'r')
     imgsurface = cairo.ImageSurface.create_from_png(tmpfile)
     imgwidth = imgsurface.get_width()
     imgheight = imgsurface.get_height()

     data = imgsurface.get_data()

     im = Image.frombuffer("RGBA",(imgwidth, imgheight),
			data ,"raw","RGBA",0,1)
     return im

More information about the Python-list mailing list