def svg2png(svgFile): svg = rsvg.Handle(file=svgFile) #This block converts the svg to png and applies naming conventions imgWidth=svg.props.width imgHeight=svg.props.height img = cairo.ImageSurface(cairo.FORMAT_ARGB32, imgWidth, imgHeight) ctx = cairo.Context(img) handler = rsvg.Handle(svgFile) handler.render_cairo(ctx) # flip x, y pat = cairo.SurfacePattern(img) # another way to flip an image on the Y axis # the order of the translate and scale are important m = cairo.Matrix() m.translate(0, img.get_height()) m.scale(1, -1) pat.set_matrix(m) dest = cairo.ImageSurface(cairo.FORMAT_ARGB32, img.get_width(), img.get_height()) cr = cairo.Context(dest) cr.set_source(pat) cr.paint() dest.write_to_png(svgFile.replace(".svg",".png"))
def render_loading_books(inpath, outpath): resSize = {"width": 256, "height": 256} with open(os.path.join(inpath, "Linking_Book.svg"), "r") as svgFile: bookSVG = parse(svgFile) layers = get_layers_from_svg(bookSVG) ratioW = resSize["width"] / float( bookSVG.documentElement.getAttribute("width")) ratioH = resSize["height"] / float( bookSVG.documentElement.getAttribute("height")) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, resSize["width"], resSize["height"]) for angle in range(0, 18): ctx = cairo.Context(surface) # Draw Book and Black Background enable_only_layers(["background", "book"], layers) svg = rsvg.Handle(data=bookSVG.toxml()) ctx.save() ctx.scale(ratioW, ratioH) svg.render_cairo(ctx) ctx.restore() # Draw Circles at appropriate angle enable_only_layers(["circles"], layers) svg = rsvg.Handle(data=bookSVG.toxml()) ctx.translate(resSize["height"] / 2, resSize["width"] / 2) ctx.rotate(math.radians(angle * (5))) ctx.translate(-resSize["width"] / 2, -resSize["height"] / 2) ctx.scale(ratioW, ratioH) svg.render_cairo(ctx) surface.write_to_png( os.path.join(outpath, "xLoading_Linking.{0:02}.png".format(angle)))
def LoadTheme(self): if str(self.msgs) == "0": self.SVGH_Face = rsvg.Handle( self.GetThemeFile('gmailread.svg', self.theme)) else: print str(self.msgs) self.SVGH_Face = rsvg.Handle( self.GetThemeFile('gmailunread.svg', self.theme))
def svg2png(svgFile): svg = rsvg.Handle(file=svgFile) #This block converts the svg to png and applies naming conventions imgWidth=svg.props.width imgHeight=svg.props.height img = cairo.ImageSurface(cairo.FORMAT_ARGB32, imgWidth, imgHeight) ctx = cairo.Context(img) handler = rsvg.Handle(svgFile) handler.render_cairo(ctx) img.write_to_png(svgFile.replace(".svg",".png"))
def set_svg(self, filename=None, data=None): """Set the SVG data to render. Use None to reset. """ if data is not None: self.svg = rsvg.Handle(data=data) elif filename is not None: self.svg = rsvg.Handle(filename) else: self.svg = None
def loadSvg(data, stroke, fill): if ((stroke == None) or (fill == None)): return rsvg.Handle(data=data) entity = '<!ENTITY fill_color "%s">' % fill data = re.sub('<!ENTITY fill_color .*>', entity, data) entity = '<!ENTITY stroke_color "%s">' % stroke data = re.sub('<!ENTITY stroke_color .*>', entity, data) return rsvg.Handle(data=data)
def update_emoji(self, msg): # code = hex(msg.data) code = "{0:x}".format(msg.data) path = self.emoji.get(code) print(code, path) if path: self.clear_screen() try: svg = rsvg.Handle(file=path) except TypeError: handle = rsvg.Handle() svg = handle.new_from_file(path) self.display_svg(svg)
def buildInstructions(boxid): img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 356,498) ctx = cairo.Context(img) #static instructions file handler= rsvg.Handle(staticSVGdir + "instructions.svg") handler.render_cairo(ctx) #the maze handler= rsvg.Handle(svgdir + "instructionsmaze.svg") handler.render_cairo(ctx) #write them out img.write_to_png(outdir + "/instructions_" + str(boxid) + ".png")
def __init__(self, wanted_width, wanted_height): gtk.DrawingArea.__init__(self) self.set_events(gdk.EXPOSURE_MASK | gdk.BUTTON_PRESS_MASK) self.connect("expose_event", self.expose) self.connect("button_press_event", self.button_press_event) self.set_tooltip_text(_("Click to turn fan animation on/off")) self.set_size_request(wanted_width, wanted_height) self.fan_border_svg = rsvg.Handle(file=build.data_dir + build.fan_border_filename) self.fan_blades_svg = rsvg.Handle(file=build.data_dir + build.fan_blades_filename) self.set_speed(0)
def surface_from_svg(self, path): import rsvg import cairo import array # NOTE: currently pygame has a bug where it switches channel # in the buffer before drawing it. The fix below is # inefficient and is not being included for now. So the svg # colors will be off # commented out pygame channel switch bug # #import re # create pygame image surface # there is a bug in pygame where it switches buffer channels # r"\2\1\4\3" #fixed_buf = re.sub (r"(.)(.)(.)(.)", r"\4\3\2\1", buf.tostring()) #surf = pygame.image.fromstring(fixed_buf, (width,height), "ARGB") svg = rsvg.Handle(file=path) width, height = svg.props.width, svg.props.width stride = width * 4 # create a character data structure because pycairo does not # seem to handle python types buf = array.array('c', chr(0) * width * height * 4) cairo_surface = cairo.ImageSurface.create_for_data( buf, cairo.FORMAT_ARGB32, width, height, stride) cairo_context = cairo.Context(cairo_surface) svg.render_cairo(cairo_context) surf = pygame.image.frombuffer(buf.tostring(), (width, height), "ARGB") return surf.convert_alpha()
def render_svg(self): self._handle = rsvg.Handle(data=self._svg_data) self._pixbuf = self._handle.get_pixbuf() self._image = gtk.Image() self._image.set_from_pixbuf(self._pixbuf) self._image.set_alignment(0.5, 0) return self._image
def _get_osm_logo(ctx, height): """ Read the OSM logo file and rescale it to fit within height. Args: ctx (cairo.Context): The cairo context to use to draw. height (number): final height of the logo (cairo units). Return a tuple (cairo group object for the logo, logo width in cairo units). """ # TODO: read vector logo logo_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', '..', 'images', 'osm-logo.svg')) if not os.path.exists(logo_path): logo_path = os.path.join(sys.exec_prefix, 'share', 'images', 'ocitysmap', 'osm-logo.svg') try: with open(logo_path, 'rb') as f: svg = rsvg.Handle(logo_path) LOG.debug('Using copyright logo: %s.' % logo_path) except IOError: LOG.warning('Cannot open logo from %s.' % logo_path) return None, None ctx.push_group() ctx.save() ctx.move_to(0, 0) factor = height / svg.props.height ctx.scale(factor, factor) svg.render_cairo(ctx) ctx.restore() return ctx.pop_group(), svg.props.width * factor
def __init__(self, halcomp, builder, useropts): self.halcomp = halcomp self.builder = builder self.ini_filename = 'savestate.sav' self.defaults = { IniFile.vars: dict(), IniFile.widgets: widget_defaults( select_widgets(self.builder.get_objects(), hal_only=False, output_only=True)) } self.ini = IniFile(self.ini_filename, self.defaults, self.builder) self.ini.restore_state(self) # A pin to use a physical switch to start the cycle self.cycle_start = hal_glib.GPin( halcomp.newpin('cycle-start', hal.HAL_BIT, hal.HAL_IN)) self.cycle_start.connect('value-changed', self.cycle_pin) # This catches the signal from Touchy to say that the tab is exposed t = self.builder.get_object('eventbox1') t.connect('map-event', self.on_map_event) t.add_events(gtk.gdk.STRUCTURE_MASK) self.cmd = linuxcnc.command() # This conects the expose event to re-draw and scale the SVG frames t = self.builder.get_object('tabs1') t.connect_after("expose_event", self.on_expose) t.connect("destroy", gtk.main_quit) t.add_events(gtk.gdk.STRUCTURE_MASK) self.svg = rsvg.Handle(file='LatheMacro.svg', ) self.active = True
def svg_to_png(in_path, out_path, width=48, height=48): """ Transform svg file into a png file at defined size Use the svg document bound as detected by rsvg library in_path -- path of the svg input file out_path -- where to save the file width -- target png width height -- target png height """ # Get input handle in_svg = rsvg.Handle(in_path) svg_w = in_svg.get_property("width") svg_h = in_svg.get_property("height") # Create output cairo surface surf = cairo.SVGSurface(StringIO.StringIO(), width, height) svgctx = cairo.Context(surf) # Rescale context to fit # TODO : take more scale type options here # TODO : support +1px border for 9 patches svgctx.scale(width / float(svg_w), height / float(svg_h)) # Render file in cairo context in_svg.render_cairo(svgctx) # Save file surf.write_to_png(out_path) surf.finish()
def _render(self, width, height): """Render our SVG to a Pygame image""" handle = rsvg.Handle(data=self.svg) originalSize = (width, height) scale = 1.0 hw, hh = handle.get_dimension_data()[:2] if hw and hh: if not width: if not height: width, height = hw, hh else: scale = float(height) / hh width = hh / float(hw) * height elif not height: scale = float(width) / hw height = hw / float(hh) * width else: # scale only, only rendering as large as it is... if width / height > hw / hh: # want it taller than it is... width = hh / float(hw) * height else: height = hw / float(hh) * width scale = float(height) / hh csrf, ctx = _cairoimage.newContext(int(width), int(height)) ctx.scale(scale, scale) handle.render_cairo(ctx) return _cairoimage.asImage(csrf) return None
def prep(self, size=None, subst=None): if subst: subst["_sizeX"] = size[ 0] # Allow the image to be changed based on the size subst["_sizeY"] = size[1] #data = self.tmpl8.safe_substitute(subst) data = self.tmpl8.generate(opt=opt, **subst) data = data.render('xml') # TODO: We need a much more sophisticated substitution, like used in web development # so that we can capture complex resizing behavior. At a minimum substitution needs to be able to evaluate expressions. else: data = self.rawsvg hdl = rsvg.Handle() hdl.write(data) hdl.close() svgSize = (hdl.get_property('width'), hdl.get_property('height')) if size is None or size == svgSize or svgSize[0] <= 0 or svgSize[ 1] <= 0: size = svgSize scale = (1.0, 1.0) else: frac = min( float(size[0]) / svgSize[0], float(size[1]) / svgSize[1]) scale = (frac, frac) # We don't want it to be distorted size = ( int(math.ceil(svgSize[0] * frac)), int(math.ceil(svgSize[1] * frac)) ) # allocate the smallest buffer that fits the image dimensions < the provided size return (hdl, size, scale)
def render_cursors(inpath, outpath): scalefactor = 4 with open(os.path.join(inpath, "Cursor_Base.svg"), "r") as svgFile: cursorSVG = parse(svgFile) layers = get_layers_from_svg(cursorSVG) svgwidth = float(cursorSVG.documentElement.getAttribute("width")) svgheight = float(cursorSVG.documentElement.getAttribute("height")) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(math.ceil(scalefactor * svgwidth)), int(math.ceil(scalefactor * svgheight))) for cursor in cursorList: ctx = cairo.Context(surface) ctx.save() ctx.set_operator(cairo.OPERATOR_CLEAR) ctx.paint() ctx.restore() enabledlayers = cursorList[cursor] enabledlayers = enabledlayers + [ l + "Shadow" for l in enabledlayers ] enable_only_layers(enabledlayers, layers) shift_all_layers(layers, *cursorOffsetList.get(cursor, [0, 0])) svg = rsvg.Handle(data=cursorSVG.toxml()) ctx.scale(scalefactor, scalefactor) svg.render_cairo(ctx) outfile = os.path.join(outpath, cursor + ".png") surface.write_to_png(outfile) scalergba.scale(outfile, outfile, scalefactor)
def draw_svg(self, svg_str): """Draws svg string to cell""" try: import rsvg except ImportError: self.draw_text(svg_str) return svg = rsvg.Handle(data=svg_str) svg_width, svg_height = svg.get_dimension_data()[:2] transx, transy = self._get_translation(svg_width, svg_height) scale_x, scale_y = self._get_scalexy(svg_width, svg_height) scale = min(scale_x, scale_y) angle = float(self.code_array.cell_attributes[self.key]["angle"]) self.context.save() self.context.rotate(-angle / 360 * 2 * math.pi) self.context.translate(transx, transy) self.context.scale(scale, scale) svg.render_cairo(self.context) self.context.restore()
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
def convert_svg_to_png(svg_file, output_file): print "processing '" + svg_file + "' file" # Get the svg files content with open(svg_file) as f: svg_data = f.read() # Get the width / height inside of the SVG doc = minidom.parse(svg_file) width = [ path.getAttribute('width') for path in doc.getElementsByTagName('svg') ][0] height = [ path.getAttribute('height') for path in doc.getElementsByTagName('svg') ][0] # if the svg width defiend in the inch convert to pixel if str(width).find("in") != -1: width = float(str(width).replace('in', '')) * 96 width = int(width) # if the svg height defiend in the inch convert to pixel if str(height).find("in") != -1: height = float(str(height).replace('in', '')) * 96 height = int(height) doc.unlink() # create the png object img = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) ctx = cairo.Context(img) handler = rsvg.Handle(None, str(svg_data)) handler.render_cairo(ctx) # write png file img.write_to_png(output_file)
def __init__(self, x, y, width=55, height=55, **kwargs): super(CloudItem, self).__init__(**kwargs) self._new = True self.x = x - width/2.0 self.y = y - height/2.0 self.width = width self.height = height self.dragging = False # find our cloud icon hanging out with the other icons. icon_paths = gtk.icon_theme_get_default().get_search_path() cloud_path = None for path in icon_paths: possible_path = os.path.join(path, "opensim-cloud.svg") if os.path.isfile(possible_path): cloud_path = possible_path break if cloud_path is None: logging.error("could not find cloud svg!") raise Exception self._cloud = rsvg.Handle(cloud_path) # keep track of inflows and outflows, for use in engine self.inflows = [] self.outflows = [] self.__needs_resize_calc = True
def __init__(self, svg, maxwidth=False, maxheight=False): png_path = os.path.splitext(svg.path)[0] + '.png' super(PNGfromSVG, self).__init__(png_path) self.svg = svg self.hdlr = rsvg.Handle(svg.path) self.maxw = maxwidth self.maxh = maxheight scale = 1 w = _w = self.hdlr.props.width h = _h = self.hdlr.props.height if self.maxw and w > self.maxw: w = self.maxw scale = float(w) / float(_w) h = scale * _h if self.maxh and h > self.maxh: h = self.maxh scale = float(h) / float(_h) w = scale * _w self.width = w self.height = h self.scale = scale self.surf = None
def get_numpy_array(self, size=256, scale=0.333): """ using rsvg library, render the svg into a cairo surface with memory defined by a numpy array, effectively rendering the svg to an array """ if self.tree_root is None: self.tree_root = self.tree_org.getroot() # get the result into a svg object (using rsvg lib) svg_object = rsvg.Handle(ET.tostring(self.tree_root)) # create a numpy array to use as our canvas data = np.zeros((size, size, 4), dtype=np.uint8) surface = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, size, size) cr = cairo.Context(surface) # fill with solid white and set scale (magic scale number) cr.set_source_rgb(1.0, 1.0, 1.0) cr.paint() cr.scale(scale, scale) # render our manipulated svg into cairo surface svg_object.render_cairo(cr) return data
def svg2png(svg_file, output_file, scale=1): # Get the svg files content svg_data = open(svg_file).read() # Get the width / height inside of the SVG doc = minidom.parseString(svg_data) width = [ path.getAttribute('width') for path in doc.getElementsByTagName('svg') ][0] height = [ path.getAttribute('height') for path in doc.getElementsByTagName('svg') ][0] width = int(round(float(re.compile('(\d+\.*\d*)\w*').findall(width)[0]))) height = int(round(float(re.compile('(\d+\.*\d*)\w*').findall(height)[0]))) doc.unlink() # Create the png img = cairo.ImageSurface(cairo.FORMAT_ARGB32, width * scale, height * scale) ctx = cairo.Context(img) ctx.scale(scale, scale) handler = rsvg.Handle(None, str(svg_data)) handler.render_cairo(ctx) img.write_to_png(output_file) print("{} ==> {}".format(svg_file, output_file))
def main(): window = gtk.Window() window.set_default_size(640, 600) window.show() window.connect("destroy", lambda w: gtk.main_quit()) scrolled_win = gtk.ScrolledWindow() scrolled_win.set_shadow_type(gtk.SHADOW_IN) scrolled_win.show() window.add(scrolled_win) canvas = goocanvas.Canvas() canvas.set_size_request(600, 450) canvas.set_bounds(0, 0, 1000, 1000) root = canvas.get_root_item() handle = rsvg.Handle("../images/circle1.svg") svgitem = CustomSvgItem(x=100, y=100, handle=handle, parent=root) svgitem.connect("button_press_event", on_press, root) r = goocanvas.Rect(parent=root, x=10, y=10, width=20, height=20) r.connect("button_press_event", on_r_press) r.props.fill_color = 'yellow' canvas.show() scrolled_win.add(canvas) gtk.main()
def render_voice_icons(inpath, outpath): resSize = {"width": 32, "height": 32} with open(os.path.join(inpath, "Voice_Chat.svg"), "r") as svgFile: uiSVG = parse(svgFile) layers = get_layers_from_svg(uiSVG) ratioW = resSize["width"] / float( uiSVG.documentElement.getAttribute("width")) ratioH = resSize["height"] / float( uiSVG.documentElement.getAttribute("height")) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, resSize["width"], resSize["height"]) for voiceUI in voiceList: ctx = cairo.Context(surface) ctx.save() ctx.set_operator(cairo.OPERATOR_CLEAR) ctx.paint() ctx.restore() enable_only_layers(voiceList[voiceUI], layers) svg = rsvg.Handle(data=uiSVG.toxml()) ctx.scale(ratioW, ratioH) svg.render_cairo(ctx) surface.write_to_png(os.path.join(outpath, voiceUI + ".png"))
def convert_svg_to_png(source_file, target_file, width, height): """ Adapted from http://guillaume.segu.in/blog/code/43/svg-to-png/ """ if not source_file: return svg = rsvg.Handle(file=source_file) if width: ratio = float(width) / svg.props.width height = int(ratio * svg.props.height) else: width = svg.props.width if height: ratio = float(height) / svg.props.height width = int(ratio * svg.props.width) else: height = svg.props.height surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) cr = cairo.Context(surface) wscale = float(width) / svg.props.width hscale = float(height) / svg.props.height cr.scale(wscale, hscale) svg.render_cairo(cr) surface.write_to_png(target_file)
def convert(data, ofile, maxwidth=0, maxheight=0): svg = rsvg.Handle(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)
def is_svg(code): """Checks if code is an svg image Parameters ---------- code: String \tCode to be parsed in order to check svg complaince """ if rsvg is None: return try: rsvg.Handle(data=code) except glib.GError: return False # The SVG file has to refer to its xmlns # Hopefully, it does so wiyhin the first 1000 characters if "http://www.w3.org/2000/svg" in code[:1000]: return True return False
def save_png(self, file_name): # Get the SVG data svg_file = open( settings.DATA_FILES_PATH + "/" + file_name + ".svg", "r") svg_data = svg_file.read() # Create the blank image surface img = cairo.ImageSurface( cairo.FORMAT_ARGB32, settings.EXPORT_IMAGE_WIDTH, settings.EXPORT_IMAGE_HEIGHT) # Get the context ctx = cairo.Context(img) # Dump SVG data to the image context handler = rsvg.Handle(None, str(svg_data)) handler.render_cairo(ctx) # Create the final png image img.write_to_png( settings.DATA_FILES_PATH + "/" + file_name + ".png") logger.info("SVG and PNG Created")