def open_svg_as_image(fn, width, height):
for i in range(10):
try:
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)
svgsurface.finish()
tmpfile.close()
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)
break
except MemoryError:
print 'Memory Error. Try again ...'
continue
else:
raise Exception('Problem loading image {0}'.format(fn))
return im
评论列表
文章目录