SVG PIL decoder
Patrick Sabin
patrick.just4fun at gmail.com
Wed Sep 30 19:08:28 EDT 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')
svgctx.scale(width/float(svgwidth),height/float(svgheight))
svg.render_cairo(svgctx)
svgsurface.write_to_png(tmpfile)
tmpfile.close()
svgsurface.finish()
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)
os.remove(tmppath)
return im
More information about the Python-list
mailing list