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
python类SVGSurface()的实例源码
def export_svg(fn, paths, size, line_with=0.1, scale_factor=None):
from cairo import SVGSurface, Context
from .ddd import spatial_sort_2d as sort
if not scale_factor:
scale_factor = size
s = SVGSurface(fn, size, size)
c = Context(s)
c.set_line_width(0.1)
paths = sort(paths)
for path in paths:
path *= scale_factor
c.new_path()
c.move_to(*path[0,:])
for p in path[1:]:
c.line_to(*p)
c.stroke()
c.save()
def export_svg(fn, paths, w, h, line_width=0.1):
from cairo import SVGSurface, Context
s = SVGSurface(fn, w, h)
c = Context(s)
c.set_line_width(line_width)
for path in paths:
c.new_path()
c.move_to(*path[0,:])
for p in path[1:]:
c.line_to(*p)
c.stroke()
c.save()
def __init__(self, width=None, height=None, name=None, bounds=None, bg=(1, 1, 1), format=None):
"""Create a new Cairo drawing.
If `bounds` is provided, it's a Bounds describing the extend of the
drawing. Otherwise, provide `width` and `height` to specify a size
explicitly.
`bg` is the background color to paint initially.
"""
if bounds is None:
assert width is not None
assert height is not None
bounds = Bounds(0, 0, width, height)
self.bounds = bounds
self.width = int(self.bounds.width)
self.height = int(self.bounds.height)
self.name, self.format = name_and_format(name, format)
if self.format == 'png':
self.surface = cairo.ImageSurface(cairo.Format.ARGB32, self.width, self.height)
elif self.format == 'svg':
self.surface = cairo.SVGSurface(self.name, self.width, self.height)
self.ctx = cairo.Context(self.surface)
self.ctx.set_antialias(cairo.Antialias.BEST)
self.ctx.set_line_cap(cairo.LineCap.ROUND)
self.ctx.set_line_join(cairo.LineJoin.MITER)
self.translate(-self.bounds.llx, -self.bounds.lly)
# Start with a solid-color canvas.
if bg:
with self.style(rgb=bg):
self.rectangle(self.bounds.llx, self.bounds.lly, self.width, self.height)
self.fill()
def _take_screenshot(self, dummy_button):
#print "Cheese!"
file_name = self._get_export_file_name()
if file_name is None:
return
# figure out the correct bounding box for what is visible on screen
x1 = self._scrolled_window.get_hadjustment().value
y1 = self._scrolled_window.get_vadjustment().value
x2 = x1 + self._scrolled_window.get_hadjustment().page_size
y2 = y1 + self._scrolled_window.get_vadjustment().page_size
bounds = goocanvas.Bounds()
bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
dest_width = bounds.x2 - bounds.x1
dest_height = bounds.y2 - bounds.y1
#print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2
dummy, extension = os.path.splitext(file_name)
extension = extension.lower()
if extension == '.eps':
surface = cairo.PSSurface(file_name, dest_width, dest_height)
elif extension == '.pdf':
surface = cairo.PDFSurface(file_name, dest_width, dest_height)
elif extension == '.svg':
surface = cairo.SVGSurface(file_name, dest_width, dest_height)
else:
dialog = gtk.MessageDialog(parent = self.canvas.get_toplevel(),
flags = gtk.DIALOG_DESTROY_WITH_PARENT,
type = gtk.MESSAGE_ERROR,
buttons = gtk.BUTTONS_OK,
message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
% (extension,))
dialog.run()
dialog.destroy()
return
# draw the canvas to a printing context
cr = cairo.Context(surface)
cr.translate(-bounds.x1, -bounds.y1)
self.canvas.render(cr, bounds, self.zoom.value)
cr.show_page()
surface.finish()
def extract_polygon_data(romset_dir, cinematic):
global polygon_data, pdata_offset
global cinematic_entries
global cinematic_counter
global video2_entries
global game_level
if cinematic:
polygon_data = open("{}/cinematic.rom".format(romset_dir)).read()
entries = cinematic_entries
level_path = "%s/level_%s" % (OUTPUT_DIR, game_level)
dirpath = "%s/cinematic/" % (level_path)
makedir(level_path)
else:
polygon_data = open("{}/video2.rom".format(romset_dir)).read()
entries = video2_entries
dirpath = "%s/common_video/" % (OUTPUT_DIR)
game_level = 0
makedir(dirpath)
for addr in entries.keys():
entry = entries[addr]
s = SVGSurface("%s/%s.svg" % (dirpath, entry['label']), 320, 200)
c = Context(s)
zoom = entry["zoom"]
x = entry["x"]
y = entry["y"]
if not isinstance(zoom, int):
zoom = 0x40 #HACK!
if not isinstance(x, int):
x = 160 #HACK!
if not isinstance(y, int):
y = 100 #HACK!
#print ("\ndecoding polygons at {}: {}".format(hex(addr), entry))
pdata_offset = addr
readAndDrawPolygon(c, COLOR_BLACK, zoom, x, y)
s.finish()
# reset structures:
cinematic_entries = {}
cinematic_counter = 0
def render(self, canvas, transparent=False):
x0,y0,x1,y1 = canvas.bbox('all')
self.markers = canvas.markers
W = int((x1 - x0 + 2*self.padding) * self.scale)
H = int((y1 - y0 + 2*self.padding) * self.scale)
ext = os.path.splitext(self.fname)[1].lower()
if ext == '.svg':
surf = cairo.SVGSurface(self.fname, W, H)
elif ext == '.pdf':
surf = cairo.PDFSurface(self.fname, W, H)
elif ext in ('.ps', '.eps'):
surf = cairo.PSSurface(self.fname, W, H)
if ext == '.eps':
surf.set_eps(True)
else: # Bitmap
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, W, H)
self.ctx = cairo.Context(surf)
ctx = self.ctx
if not transparent:
# Fill background
ctx.rectangle(0,0, W,H)
ctx.set_source_rgba(1.0,1.0,1.0)
ctx.fill()
ctx.scale(self.scale, self.scale)
ctx.translate(-x0 + self.padding, -y0 + self.padding)
if self.draw_bbox:
last = len(canvas.shapes)
for s in canvas.shapes[:last]:
bbox = s.bbox
r = canvas.create_rectangle(*bbox, line_color=(255,0,0, 127), fill=(0,255,0,90))
for s in canvas.shapes:
self.draw_shape(s)
if ext in ('.svg', '.pdf', '.ps', '.eps'):
surf.show_page()
else:
surf.write_to_png(self.fname)